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

题目来源:

  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

posted @ 2015-10-12 21:53  Ry_Chen  阅读(418)  评论(0编辑  收藏  举报