Swap Nodes in Pairs

来源:互联网 发布:软件注册过期怎么办 编辑:程序博客网 时间:2024/06/06 13:14

题目:

Given a linked list, swap every two adjacent nodes and return its head.

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

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

解题思路:

这题主要涉及到链表的基本操作。加一个头结点,操作起来会很方便。另外配了一个示意图


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution:
    # @param {ListNode} head
    # @return {ListNode}
    def swapPairs(self, head):
        sentry_node = ListNode(0)
        sentry_node.next = head
        pre,suc = sentry_node,head
        while (suc and suc.next):
            pre.next = suc.next
            suc.next = pre.next.next
            pre.next.next = suc
            pre, suc = suc,suc.next
        return sentry_node.next
        

0 0