1、C
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseBetween(struct ListNode* head, int left, int right){ if(right==left)return head; struct ListNode* h = (struct ListNode*)malloc(sizeof(struct ListNode)); h->next = head; struct ListNode* q = h; for(int i=0;i<left-1;i++){ q = q->next; } struct ListNode* p = q; q = q->next; struct ListNode* r = q->next; for(int i=0;i<right-left;i++){ struct ListNode* t = r->next; r->next = q; q = r; r = t; } struct ListNode* ll = p->next; p->next = q; ll->next = r; return h->next; }
2、C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int left, int right) { if(right==left)return head; ListNode* h = new ListNode(-1); h->next = head; ListNode * q = h; for(int i=0;i<left-1;i++){ q = q->next; } ListNode *p = q; q = q->next; ListNode * r = q->next; for(int i=0;i<right-left;i++){ ListNode* t = r->next; r->next = q; q = r; r = t; } ListNode* ll = p->next; p->next = q; ll->next = r; return h->next; } };
3、JAVA
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseBetween(ListNode head, int left, int right) { if(left==right)return head; ListNode h = new ListNode(-1); h.next = head; ListNode q = h; for(int i=0;i<left-1;i++){ q = q.next; } ListNode p = q; q = q.next; ListNode r = q.next; for(int i=0;i<right-left;i++){ ListNode t = r.next; r.next = q; q = r; r = t; } ListNode ll = p.next; p.next = q; ll.next = r; return h.next; } }
4、Python
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def reverseBetween(self, head, left, right): """ :type head: ListNode :type left: int :type right: int :rtype: ListNode """ if left == right: return head h = ListNode() h.next = head q = h for i in range(left-1): q = q.next p = q q = q.next r = q.next for i in range(right-left): t = r.next r.next = q q = r r = t ll = p.next p.next = q ll.next = r return h.next标签:II,head,ListNode,struct,val,int,next,链表,算法 From: https://www.cnblogs.com/cmkbk/p/17197094.html