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.
给定链表和位置m,n,要求对位置m,n之间的链表逆序。
使用辅助节点dummyHead,遍历链表并计数,找到位置m-1出的节点back和位置n处的节点(可能为NULL)front,然后以back为辅助头结点,front为尾节点进行链表逆序即可。
AC code:
/**
* 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 *dummyHead=new ListNode(0);
ListNode *front=dummyHead;
ListNode *back=dummyHead;
dummyHead->next=head;
for(int i=1;i<m;i++) //移动到待逆序部分的前一个节点
back=back->next;
for(int i=0;i<=n;i++) //移动到带逆序部分的后一个节点
front=front->next;
//开始逆序
ListNode *previous,*current;
previous=back->next;
current=previous->next;
while(current!=front)
{
previous->next=current->next;
current->next=back->next;
back->next=current;
current=previous->next;
}
current=dummyHead->next;
delete dummyHead;
return current;
}
};