lintcode-36-翻转链表 II

时间:2022-12-18 09:34:20

36-翻转链表 II

翻转链表中第m个节点到第n个节点的部分

注意事项

m,n满足1 ≤ m ≤ n ≤ 链表长度

样例

给出链表1->2->3->4->5->null, m = 2 和n = 4,返回1->4->3->2->5->null

挑战

在原地一次翻转完成

标签

链表

思路

借助2个空的节点,置于链表头部,一次遍历链表,找到翻转子链尾部subEnd,不翻转子链尾部lastEnd,头部nextHead,以及当前节点nowNode,在遍历时,将nowNode插入lastEnd与subEnd之间。最后,将翻转子链与nextHead相连。

code

/**
* Definition of singly-linked-list:
*
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The head of linked list.
* @param m: The start position need to reverse.
* @param n: The end position need to reverse.
* @return: The new head of partial reversed linked list.
*/
ListNode *reverseBetween(ListNode *head, int m, int n) {
// write your code here ListNode newHead1(-1), newHead2(-1);
newHead1.next = &newHead2;
newHead2.next = head; ListNode *nowNode=head, *subHead=head, *subEnd=NULL, *lastEnd=&newHead1, *nextHead=NULL;
int i=1;
while(nowNode != NULL) {
if(i <= m) {
lastEnd = lastEnd->next;
subEnd = nowNode;
nextHead = nowNode;
nowNode = nowNode->next;
i++;
}
else if(i <= n) {
ListNode *temp = nowNode->next;
nextHead->next = NULL;
lastEnd->next = nowNode;
lastEnd->next->next = subEnd;
subEnd = nowNode;
nowNode = temp;
i++;
}
else {
nextHead->next = nowNode;
break;
}
} if(m == 1) {
return lastEnd->next;
}
else {
return head;
}
}
};