[LeetCode] Reverse Linked List II,leetcodelinked
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
解題思路
解題思路與上一篇Reverse Linked List類似,只不過這裡是反轉部分鏈表。
因此,只需將m到n部分翻轉,然後將m的首碼beforeM指向該部分反轉後的頭結點即可。如果beforeM為NULL,則m=1,m到n部分的頭結點即為鏈表的頭結點。
實現代碼
//Runtime: 4 ms#include <iostream>#include <cstdlib>#include <cmath>using namespace std;struct ListNode{ int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};class Solution {public: ListNode* reverseBetween(ListNode* head, int m, int n) { ListNode *cur = head; ListNode *beforeM = NULL; for (int i = 1; i < m; i++) { beforeM = cur; cur = cur->next; } ListNode *localhead = cur; ListNode *pre = cur; cur = cur->next; int count = n - m; while (count--) { pre->next = cur->next; cur->next = localhead; localhead = cur; cur = pre->next; } if (beforeM == NULL) { head = localhead; } else { beforeM->next = localhead; } return head; }};void printList(ListNode *head){ while(head != NULL) { cout<<head->val<<" "; head = head->next; } cout<<endl;}void dropList(ListNode *head){ if (head == NULL) return; ListNode *temp; while (head != NULL) { temp = head->next; delete head; head = temp; }}int main(){ ListNode *head = new ListNode(0); ListNode *cur = head; for (int i = 0; i < 10; i++) { ListNode *newnode = new ListNode(floor(rand()%77)); cur->next = newnode; cur = newnode; } printList(head); Solution s; head = s.reverseBetween(head, 2, 5); printList(head); dropList(head);}