美文网首页
Leetcode-第24题:Swap Nodes in Pair

Leetcode-第24题:Swap Nodes in Pair

作者: 八刀一闪 | 来源:发表于2016-09-24 16:53 被阅读25次

题目:

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.

代码:

def swapPairs(self, head):
    """
    :type head: ListNode
    :rtype: ListNode
    """
    pre = None
    p1 = head
    while p1!=None and p1.next!=None:
        p2 = p1.next
        t = p2.next
        p2.next = p1
        p1.next = t
        if pre == None:
            head = p2
        else:
            pre.next = p2
        pre = p1
        p1 = p1.next
    return head

相关文章

网友评论

      本文标题:Leetcode-第24题:Swap Nodes in Pair

      本文链接:https://www.haomeiwen.com/subject/itvxyttx.html