快樂的LeetCode --- 24. 兩兩交換鏈表中的節點

題目描述:

  給定一個鏈表,兩兩交換其中相鄰的節點,並返回交換後的鏈表。你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

示例:

給定 1->2->3->4, 你應該返回 2->1->4->3.

解題思路1:
在這裏插入圖片描述
每次做完一對之後,讓p指向當前a的位置

在這裏插入圖片描述


C++寫法:

代碼:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        auto dummy = new ListNode(-1);
        dummy -> next = head;

        for(auto p = dummy; p -> next && p -> next -> next;)
        {
            auto a = p -> next, b = a -> next;
            p -> next = b;
            a -> next = b -> next;
            b -> next = a;
            p = a;
        }
        return dummy -> next;
    }
};

python寫法:

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

class Solution(object):
    def swapPairs(self, head):

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

        p = dummy
        while p.next and p.next.next:
            a = p.next
            b = a.next
            p.next = b
            a.next = b.next
            b.next = a
            p = a

        return dummy.next

題目來源:

https://leetcode-cn.com/problems/swap-nodes-in-pairs

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