首页 > 代码库 > [leetcode]Swap Nodes in Pairs @ Python

[leetcode]Swap Nodes in Pairs @ Python

原题地址:http://oj.leetcode.com/problems/swap-nodes-in-pairs/

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.

题意:将链表中的节点两两交换。Given 1->2->3->4, you should return the list as 2->1->4->3.

解题思路:这题主要涉及到链表的节本操作。加一个头结点,操作起来会很方便。另外配了一个示意图 [本图是我asrman原创]

代码:

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # @param a ListNode    # @return a ListNode    def swapPairs(self, head):        pre = ListNode(0)        pre.next = head        curr = head        head = pre        while curr and curr.next:      # curr =1, curr.next =2            pre.next = curr.next       # 0 --> 2            curr.next = pre.next.next  # 1 --> 3  # curr.next.next            pre.next.next = curr       # 3 --> 1            pre = curr                 # pre = 1            curr = curr.next           # curr= 3        return head.next

参考:

https://oj.leetcode.com/discuss/3608/seeking-for-a-better-solution

[leetcode]Swap Nodes in Pairs @ Python