一、问题介绍
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
二、思路解析
对于链表的问题,需要建一个preHead,连上原链表的头结点,这样的话就算头结点变动了,我们还可以通过preHead->next来获得新链表的头结点。
三、代码实现
/**
* 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) {
ListNode *dummy = new ListNode(0), *pre = dummy;
dummy->next = head;
for (int i = 1; i <= m - 1; ++i) pre = pre->next;
ListNode *cur = pre->next;
for (int i = m; i <= n - 1; ++i) {
ListNode *t = cur->next;
cur->next = t->next;
t->next = pre->next;
pre->next = t;
}
return dummy->next;
}
};
来源:https://blog.csdn.net/ixiaowei1993/article/details/100935222