Swap Nodes in Pairs

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

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.

 题目:将列表中结点两两交换

注意:==的书写和reverse的代码别写错

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     # @param {ListNode} head
 9     # @return {ListNode}
10     def swapPairs(self, head):
11         if head==None or head.next==None:
12             return head
13         dummy=ListNode(0)
14         dummy.next=head
15         p=dummy
16         while p.next and p.next.next:               #reverse就是将后面的结点依次前置,此处只需前置一项
17             tmp=p.next.next; p.next.next=tmp.next   #将前置项删除   
18             tmp.next=p.next; p.next=tmp             #将前置项前置
19             p=p.next.next
20         return dummy.next

 

 

 
posted @ 2015-07-01 09:29  小榛子  阅读(104)  评论(0编辑  收藏  举报