3-3

24.两两交换链表中的节点

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

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

示例:

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

A standard python solution:

# 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):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next: return head
        
        # 首先定义两个指针
        # 指针cur用来实现交换
        # 指针dummy用于最后的输出
        cur = dummy = ListNode(0)
        dummy.next = head
        
        while cur.next and cur.next.next:
            
            # 除了cur外,要完成交换过程,还需要另外两个指针:first和second,
            # 这两个指针的位置是动态变化的,在每一次while循环开始时:
            first = cur.next    # 指针first都会指向cur的下一个位置
            sec = cur.next.next # 指针sec都会指向cur的下下一个位置
            
            # 交换过程由以下四行代码完成,具体的交换过程如下面的图示所示
            cur.next = sec
            first.next = sec.next
            sec.next = first
            cur = cur.next.next
        return dummy.next

交换过程:

图片来源:https://raw.githubusercontent.com/yuzhoujr/spazzatura/master/img_box/24.jpg

猜你喜欢

转载自www.cnblogs.com/tbgatgb/p/11108090.html
3-3