交换链表中相邻节点,要求不能改变节点的值,只能交换节点本身

示例:

输入:2->3->4->5 

输出:3->2->5->4

python解决方案:

# 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
        """
        prev = ListNode(0)
        p = prev
        prev.next = head
        i = 1
        while head and head.next:
            prev.next,head.next.next,head.next = head.next,head,head.next.next
            prev,head = head,head.next
        return p.next

猜你喜欢

转载自www.cnblogs.com/wenqinchao/p/10675676.html