标签:
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.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: /* Ex: 1->2->3->4->5->NULL return: 1->4->3->2->5->NULL */ ListNode* reverseBetween(ListNode* head, int m, int n) { if(head==NULL)return head; ListNode* mpre=NULL; //Node before No.m ListNode* p=head; for(int i=1;i<m;i++) { mpre=p; p=p->next; } /*循环结束后,mpre指向需要reverse的前一个结点,p指向需要reverse的第一个结点,即第m-1个结点 mpre data为1的结点 p data为2的结点 */ ListNode* nend=p; //记录下此时的p,reverse后,这个结点循环后是第n个结点 ListNode* ppre=p; //记录下此时的p,用来交换,这个结点循环后是第m个结点 p=p->next; /* nend data为2的结点 ppre data为2的结点 p data为3的结点 */ for(int i=m;i<n;i++) //swap ppre and p { ListNode* tmp=p->next; p->next=ppre; ppre=p; p=tmp; } /* p data为5的结点 ppre data为4的结点 nend data为2的结点 */ nend->next=p; //nend接上 if(mpre) //mpre接上 mpre->next=ppre; else head=ppre; return head; } };
leetcode No92. Reverse Linked List II
标签:
原文地址:http://blog.csdn.net/u011391629/article/details/52163831