[List] Leetcode node (24) the list of the exchange twenty-two

topic

Given a list pairwise exchange with adjacent nodes, and return the list to the exchange. You can not just simply change the internal node values , but need to be the actual node exchange.

Example:

给定 1->2->3->4, 你应该返回 2->1->4->3.

answer

To open a new node in the list head and connected thead, assigned to a new variable t, pointing to the next node in the list changes by t, thead returned unchanged Finally, when there are two consecutive nodes next start switching point, because pairwise exchange, so after the completion of each exchange, t take two steps back.

The idea is as follows:

By code is as follows: The time complexity of O (n), the spatial complexity is O (1)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        thead = ListNode(0)
        thead.next = head
        t = thead
        while t.next and t.next.next:
            a, b = t.next, t.next.next
            t.next, a.next, b.next = b, b.next, a
            t = t.next.next
        return thead.next

## 注释
# class Solution:
#     def swapPairs(self, head: ListNode) -> ListNode:
#         thead = ListNode(0)
#         thead.next = head
#         t = thead  # thead留在首部,返回时使用
#         while t.next and t.next.next:  # 有两个数才交换
#             a, b = t.next, t.next.next
#             t.next, a.next, b.next = b, b.next, a  # t先断a,a断b,b再接a
#             t = t.next.next  # 往后走两步,准备下两个数交换
#         return thead.next

Guess you like

Origin www.cnblogs.com/ldy-miss/p/11924154.html