您的位置:首页 > Web前端 > Node.js

[LeetCode] 24. Swap Nodes in Pairs 交换相邻结点 @python

2018-03-18 13:45 609 查看

Description

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.

给定一个链表,对每两个相邻的结点作交换并返回头节点。

例如:

给定 1->2->3->4,你应该返回 2->1->4->3。

你的算法应该只使用额外的常数空间。不要修改列表中的值,只有节点本身可以​​更改。

Solution

核心点:另加一个头结点。注意指向顺序!



# -*- coding: utf-8 -*-
"""
Created on Sat Mar 17 20:55:41 2018

@author: Saul
"""

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

class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
pre, cur = dummy, head
while cur and cur.next:
pre.next = cur.next  # 0->2
cur.next = pre.next.next # 1->3
pre.next.next = cur
pre = cur
cur = cur.next
return dummy.next
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python leetcode 算法