[Leetcode] 92. Reverse Linked List II
阿新 • • 發佈:2018-11-19
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ const static int x=[]{ std::ios::sync_with_stdio(false); std::cin.tie(NULL); return NULL; }(); class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if(m==n) return head; ListNode* cur_next;//當前遍歷節點的下一個節點 ListNode* cur; //當前遍歷節點 ListNode* cur_prev; //當前遍歷節點的上一個節點 ListNode* tail; //反轉節點的最後一個節點 ListNode* prev; if(m==1){ tail=head; cur=head; cur_prev=NULL; cur_next=cur->next; int i=m; for(int i=m;i<n+1;i++){ cur->next=cur_prev; cur_prev=cur; cur=cur_next; if(cur!=NULL) cur_next=cur->next; } head=cur_prev; tail->next=cur; }else{ cur=head; int i=1; while(i<m-1){ cur=cur->next; i++; } prev=cur; cur=cur->next; tail=cur; cur_prev=NULL; cur_next=cur->next; for(int i=m;i<n+1;i++){ cur->next=cur_prev; cur_prev=cur; cur=cur_next; if(cur!=NULL) cur_next=cur->next; } tail->next=cur; prev->next=cur_prev; } return head; } };