Leetcode024 swap-nodes-in-pairs

两两交换链表中的节点

题目描述:

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例

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

解题思路:

主要考察对链表中节点交换的使用

对于交换链表中A->B->C->D中的A和B需要做如下操作:

1.将A指向C
2.将B指向A
3.将C节点作为下次交换的开始节点

  • 先创建一个虚拟头结点cur,将其添加在head链表的头部
  • 用指针n1,n2分别表示A和B的位置,用指针nxt表示C的位置
  • 之后便是将A指向C(n1.next = nxt),B指向A(n2.next = n1),同时将B作为头结点(cur.next = n2),然后将cur节点的位置移动到C 前面,即A的位置上(cur = n1),继续下一轮C与D的交换

Python源码:

# 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:
        if head is None:
            return head
        cur = ListNode(0)
        cur.next = head
        first = cur
        while cur.next and cur.next.next:
            n1 = cur.next
            n2 = n1.next
            nxt = n2.next
            n1.next = nxt
            n2.next = n1
            cur.next = n2

            cur = n1
        return first.next

欢迎关注我的github:https://github.com/UESTCYangHR

猜你喜欢

转载自blog.csdn.net/dzkdyhr1208/article/details/89204776