力扣—— Swap Nodes in Pairs(两两交换链表中的节点) python实现

题目描述:

中文:

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

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

示例:

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

英文:

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:

Given 1->2->3->4, you should return the list as 2->1->4->3.

# 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 head is None or head.next is None: 
            return head

        dummyhead = ListNode(0)
        dummyhead.next = head

        pre = dummyhead
        curr = head
        while curr is not None and curr.next is not None:
            tmp = curr.next
            curr.next = tmp.next
            tmp.next = pre.next 
            pre.next = tmp
            pre = curr
            curr = curr.next
        return dummyhead.next

题目来源:力扣

猜你喜欢

转载自www.cnblogs.com/spp666/p/11651009.html