Skip to content

Latest commit

 

History

History
59 lines (40 loc) · 1.2 KB

0024. Swap Nodes in Pairs.md

File metadata and controls

59 lines (40 loc) · 1.2 KB

题目

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes. Only nodes itself may be changed.

Example 1:

img

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [1]
Output: [1]

Constraints:

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

solution

给了一个链表,要求交换所有相邻的两个节点,并返回链表头。注意,不能修改节点的值,而只能对指针进行操作。循环链表,每次交换两个节点,直到链表末尾。

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        head2 = ListNode(0)
        p = head2
        while head and head.next:
            t = head.next
            head.next = t.next
            t.next = head
            p.next = t
            p = head
            head = head.next
        return head2.next