天天看點

打卡群刷題總結0627——兩兩交換連結清單中的節點

題目:24. 兩兩交換連結清單中的節點

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

給定一個連結清單,兩兩交換其中相鄰的節點,并傳回交換後的連結清單。

你不能隻是單純的改變節點内部的值,而是需要實際的進行節點交換。

示例:

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

解題:

1、循環,是局部的“連結清單反轉”。

代碼:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head

        # 添加節點
        p = ListNode(0)
        p.next = head
        head = p

        p = head
        while p and p.next and p.next.next:
            first = p.next
            second = p.next.next
            first.next = second.next
            p.next = second
            second.next = first
            p = first
        return head.next           

複制