1 题目
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
2 尝试解
/**
* 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(head == NULL) return head;
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* slow;
ListNode* fast;
slow = dummy;
fast = dummy;
for(int i = 1; i < m; i++){
slow = slow->next; //to pre node of m,e.g. 1
}
for(int i = 1; i <= n; i++){
fast = fast->next; //to pre node of n,e.g. 4
}
while(slow->next != fast){
ListNode* tochange = slow->next; //e.g. 2
slow->next = tochange->next; // 1->3->4->5->NULL 2->3->4->5->NULL
tochange->next = fast->next; //1->3->4->5->NULL 2->5
fast->next = tochange; //1->3->4->2->5
}
return dummy->next;
}
};
3 标准解
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode *dummy = new ListNode(0), *pre = dummy, *cur;
dummy -> next = head;
for (int i = 0; i < m - 1; i++) {
pre = pre -> next;
}
cur = pre -> next;
for (int i = 0; i < n - m; i++) {
ListNode* temp = pre -> next;
pre -> next = cur -> next;
cur -> next = cur -> next -> next;
pre -> next -> next = temp;
}
return dummy -> next;
}
};