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.
题意
翻转制定位置的链表节点。比如
1->2->3->4->5->NULL
,
m
= 2 and
n
= 4,
要翻转第二到第四个节点 即把
2->3->4翻转
成4->3->2
得到
1->4->3->2->5->NULL
要求:不使用额外空间,并且遍历一遍完成。
题解
因为要不适用额外空间,并且一次完成,增加了不小的难度。
下面是我自己做的示意图,第一条原始数据,prev指针指向要翻转的第一个节点,cur指针指向prev的下一个元素
第一步 prev->next=cur->next
第二步 cuir->next=head->next
第三部 head->next=cur;
这样一轮翻转完成,cur指向新的prev->next。然后采取同样的步骤进行翻转,反转次数为n-m。
注意,我这里的head不是链表头,而是第m个节点的父节点。所以做题的时候得添加一个临时父节点以防边界问题出现。
/**
* 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 temp_head(-1);
ListNode *prev=&temp_head;
temp_head.next=head;
for(int i=0;i<m-1;i++)
prev=prev->next;
ListNode *newhead=prev;
prev=newhead->next;
ListNode *cur=prev->next;
for(int i=0;i<n-m;i++)
{
prev->next=cur->next;
cur->next=newhead->next;
newhead->next=cur;
cur=prev->next;
}
return temp_head.next;
}
};