您的位置:首页 > 其它

Leetcode 92. Reverse Linked List II

2018-02-06 09:02 501 查看
原题:

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.

解决方法:

翻转链表的变种,需要翻转n-m+1个节点,也可以看成,从m开始,需要将后面的n-m个节点提到n-1的节点后面。

代码:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if (!head || m==n)
return head;

ListNode dummy(INT_MIN), *prev=&dummy;
prev->next = head;

int index = 1;
while(head){
if (index >= m && index < n){
ListNode* cur = head;
ListNode* next = head->next;

cur->next = next->next;
next->next = prev->next;
prev->next = next;
}else if (index >=n){
break;
}else{
prev = prev->next;
head = head->next;
}

++index;
}

return dummy.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C Leetcode