码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode]Swap Nodes in Pairs @ Python

时间:2014-05-01 06:44:21      阅读:339      评论:0      收藏:0      [点我收藏+]

标签:des   com   http   style   blog   class   div   img   c   code   java   

原题地址:http://oj.leetcode.com/problems/swap-nodes-in-pairs/

题意:将链表中的节点两两交换。Given 1->2->3->4, you should return the list as 2->1->4->3.

解题思路:这题主要涉及到链表的操作,没什么特别的技巧,注意不要出错就好。最好加一个头结点,操作起来会很方便。

代码:

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

class Solution:
    # @param a ListNode
    # @return a ListNode
    def swapPairs(self, head):
        if head == None or head.next == None:
            return head
        dummy = ListNode(0); dummy.next = head
        p = dummy
        while p.next and p.next.next:
            tmp = p.next.next
            p.next.next = tmp.next
            tmp.next = p.next
            p.next = tmp
            p = p.next.next
        return dummy.next
        
mamicode.com,码迷

 

[leetcode]Swap Nodes in Pairs @ Python,码迷,mamicode.com

[leetcode]Swap Nodes in Pairs @ Python

标签:des   com   http   style   blog   class   div   img   c   code   java   

原文地址:http://www.cnblogs.com/zuoyuan/p/3701919.html

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