LeetCode-92-Reverse Linked List II
阿新 • • 發佈:2019-02-02
reverse posit 思路 span pan next between return position
算法描述:
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
解題思路:鏈表題,首先要畫圖。四個指針,頭指針,前指針,臨時指針。
ListNode* reverseBetween(ListNode* head, int m, intn) { ListNode* dummy = new ListNode(-1); dummy->next = head; ListNode* prev = dummy; ListNode* cur = dummy; for(int i=1; i < m; i++) prev = prev->next; cur = prev->next; for(int i =m; i<n; i++){ ListNode* temp = cur->next; cur->next = temp->next; temp->next =prev->next; prev->next = temp; } return dummy->next; }
LeetCode-92-Reverse Linked List II