首页 > 编程语言 > 详细

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

时间:2015-10-12 22:24:47      阅读:272      评论:0      收藏:0      [点我收藏+]

题目来源:

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


 

题意分析:

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


 

题目思路:

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


 

代码(python):

技术分享
 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def swapPairs(self, head):
 9         """
10         :type head: ListNode
11         :rtype: ListNode
12         """
13         if head == None:
14             return None
15         ans = ListNode(0)
16         ans.next = head
17         tmp = ans
18         while tmp.next and tmp.next.next:
19             t = tmp.next.next
20             tmp.next.next = t.next
21             t.next = tmp.next
22             tmp.next = t
23             tmp = tmp.next.next
24         return ans.next
View Code

 


 

转载请注明出处:http://www.cnblogs.com/chruny/p/4872950.html

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

原文:http://www.cnblogs.com/chruny/p/4872950.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!