快樂的LeetCode --- 92. 反轉鏈表 II

題目描述:

反轉從位置 m 到 n 的鏈表。請使用一趟掃描完成反轉。

說明: 1 ≤ m ≤ n ≤ 鏈表長度。

示例:

輸入: 1->2->3->4->5->NULL, m = 2, n = 4
輸出: 1->4->3->2->5->NULL

解題思路1:
在這裏插入圖片描述


代碼1:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseBetween(self, head, m, n):
        if m == n:
            return head

        dummy = ListNode(-1)
        dummy.next = head

        a = d = dummy
        for i in range(m-1):
            a = a.next
        for j in range(n):
            d = d.next
        
        b = a.next
        c = d.next

        p = b
        q = b.next
        while(q!=c):
            o = q.next
            q.next = p
            p = q
            q = o

        b.next = c
        a.next = d

        return dummy.next

c++寫法

/**
 * 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) {
        if (m == n)  return head;
        
        auto dummy = new ListNode(-1);
        dummy -> next = head;

        auto a = dummy, d = dummy;
        for(int i=0;i < m-1; i ++) a = a -> next;
        for(int i=0;i < n; i ++) d = d -> next;  

        auto b = a -> next, c = d -> next;

        for(auto p=b, q = b -> next; q != c;){
            auto o = q -> next;
            q -> next = p;
            p = q, q = o;
        }
        b -> next = c;
        a -> next = d;

        return dummy -> next;
    }
};

題目來源:

https://leetcode-cn.com/problems/reverse-linked-list-ii/

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