LeetCode 092: Reverse Linked List II

来源:互联网 发布:hadoop ssh 端口 编辑:程序博客网 时间:2024/04/30 03:50

092. Reverse Linked List II

Difficulty: Medium
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.

思路

只反转链表中的一段。
a->b->c->d->e, m=2, n=4。
依次调整结点,从第m+1个结点开始,调整结点c的过程可以看为先将结点c删除,再插到结点a后。由此,结点a也就是第m-1个结点需要保存下来,且为避免m=1时的特殊处理,链表创建头结点,最后返回头结点的下一结点。
因此,除头结点外,需要定义3个指针,分别指向第m-1个结点,当前遍历的结点以及它的前一结点。注,当前遍历结点的前一结点也未改变过,一直为第m个结点。

代码

[C++]

class Solution {public:    ListNode* reverseBetween(ListNode* head, int m, int n) {        if (m == n)            return head;        ListNode *pStart = new ListNode(-1);        pStart->next = head;        ListNode *pPrev = pStart;        for (int i = 0; i < m - 1; ++i)             pPrev = pPrev->next;        ListNode *pNode = pPrev->next;        ListNode *pNext = NULL;        for (int i = 0; i < n - m; ++i) {            pNext = pNode->next;            pNode->next = pNext->next;            pNext->next = pPrev->next;            pPrev->next = pNext;        }        ListNode *res = pStart->next;        delete pStart;        return res;    }};
0 0