[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 = None

class Solution:
    # @param a ListNode
    # @return a ListNode
    def swapPairs(self, head):
        dummy = ListNode(0)
        dummy.next = head
        pre, curr = dummy, head
        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        # 2 --> 1
            pre, curr = curr,curr.next  # pre = 1, curr= 3
        return dummy.next

参考:

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

原文地址:https://www.cnblogs.com/asrman/p/3972094.html