[leetcode]Swap Nodes in Pairs @ Python

妖精的绣舞 提交于 2020-02-22 06:20:35

原题地址: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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!