LeetCode 92. 反轉連結串列 II(C、C++、python)
阿新 • • 發佈:2018-12-16
反轉從位置 m 到 n 的連結串列。請使用一趟掃描完成反轉。
說明:
1 ≤ m ≤ n ≤ 連結串列長度。
示例:
輸入: 1->2->3->4->5->NULL, m = 2, n = 4 輸出: 1->4->3->2->5->NULL
C
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseBetween(struct ListNode* head, int m, int n) { struct ListNode* pre=(struct ListNode*)malloc(sizeof(struct ListNode)); pre->val=-1; pre->next=head; int count=0; m++; n++; struct ListNode* tmp=pre; struct ListNode* start=NULL; struct ListNode* pcur=NULL; struct ListNode* last=NULL; struct ListNode* p2=NULL; while(tmp) { count++; if(count==m-1) { start=tmp; pcur=start->next; } if(count==n) { p2=tmp; last=p2->next; p2->next=NULL; break; } tmp=tmp->next; } struct ListNode* pnext=NULL; struct ListNode* pnew=last; while(pcur) { pnext=pcur->next; pcur->next=pnew; pnew=pcur; pcur=pnext; } start->next=pnew; return pre->next; }
C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if(m==n) { return head; } ListNode* pre=new ListNode(-1); pre->next=head; m++; n++; ListNode* tmp=pre; int count=0; ListNode* start=NULL; ListNode* last=NULL; ListNode* pcur=NULL; ListNode* p2=NULL; while(tmp) { count++; if(count==m-1) { start=tmp; pcur=start->next; } if(count==n) { p2=tmp; last=p2->next; p2->next=NULL; break; } tmp=tmp->next; } ListNode* pnext=NULL; ListNode* pnew=last; while(pcur) { pnext=pcur->next; pcur->next=pnew; pnew=pcur; pcur=pnext; } start->next=pnew; return pre->next; } };
python
class Solution: def reverseBetween(self, head, m, n): """ :type head: ListNode :type m: int :type n: int :rtype: ListNode """ pre=ListNode(-1) pre.next=head m+=1 n+=1 tmp=pre count=0 while tmp: count+=1 if count==m-1: start=tmp pcur=start.next if count==n: last=tmp pnew=last.next last.next=None break tmp=tmp.next while pcur: pnext=pcur.next pcur.next=pnew pnew=pcur pcur=pnext start.next=pnew return pre.next