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

[LeetCode]题解(python):024-Swap Nodes in Pairs

2015-10-12 21:53 681 查看
[b]题目来源:[/b]

  https://leetcode.com/problems/swap-nodes-in-pairs/

[b]题意分析:[/b]

  给定一个链表,每两个相邻节点就行交换。比如1->2->3->4,得到2->1->4->3。要求不能改变节点的值,不能新建链表。

[b]题目思路:[/b]

  这题是考链表的操作。首先建立一个头节点,将头节点指向第二个节点,然后再指向第一个节点,最后指向第三个节点,然后指针跳到第二个节点重复。

[b]代码(python):[/b]

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

class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return None
ans = ListNode(0)
ans.next = head
tmp = ans
while tmp.next and tmp.next.next:
t = tmp.next.next
tmp.next.next = t.next
t.next = tmp.next
tmp.next = t
tmp = tmp.next.next
return ans.next


View Code

转载请注明出处:http://www.cnblogs.com/chruny/p/4872950.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: