码迷,mamicode.com
首页 > 其他好文 > 详细

Swap Nodes in Pairs

时间:2015-07-01 09:51:57      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

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

 

 

 

Swap Nodes in Pairs

标签:

原文地址:http://www.cnblogs.com/lzsjy421/p/4612374.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!