LeetCode:92. Reverse Linked List II

一、问题介绍

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

二、思路解析

对于链表的问题,需要建一个preHead,连上原链表的头结点,这样的话就算头结点变动了,我们还可以通过preHead->next来获得新链表的头结点。

①先找到m-1节点,以及m节点。对应的就是下面的pre和cur

②遍历找到n节点和n+1节点。对应的就是下面的t和t->next

③开始链接节点:

     1. 取下m,使m节点的下一个指向n+1。对应的就是下面的cur->next = t->next

         此时,m已经拿走了,这样pre->next指向的就是原来m+1的那个节点了。

     2. n节点的下一个指向m+1。对应的就是下面的t->next = pre->next

     3. n节点放到m的位置,m-1的next指向n节点。对应的就是pre->next = t;

 

三、代码实现

/**
 * 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) {
       ListNode *dummy = new ListNode(0), *pre = dummy;
        dummy->next = head;
        for (int i = 1; i <= m - 1; ++i) pre = pre->next;
        ListNode *cur = pre->next;
        for (int i = m; i <= n - 1; ++i) {
            ListNode *t = cur->next;
            cur->next = t->next;
            t->next = pre->next;
            pre->next = t;
        }
        return dummy->next;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章