您的位置:首页 > 其它

92. Reverse Linked List II

2015-08-06 16:29 281 查看
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节点,从节点m到n依次反转指针,然后把翻转后的串连起来即可。注意在反转指针的时候,需要三个指针,分别为pre、p和pafter。

/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == NULL)return NULL;
//为了操作方便,添加额外的头结点tmpHead
ListNode *tmpHead = new ListNode(0), *p = head, *mpre = tmpHead;
tmpHead->next = head;
for(int i = 1; i < m; i++)
{mpre = p; p = p->next;}//找到m节点
ListNode *pafter = p->next, *mbackup = p;
for(int i = 1; i <= n-m; i++)
{//反转m到n的指针
ListNode *pre = p;
p = pafter;
pafter = pafter->next;
p->next = pre;
}
//连接
mbackup->next = pafter;
mpre->next = p;
head = tmpHead->next;
delete tmpHead;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: