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

[leetcode]Swap Nodes in Pairs @ Python

时间:2014-09-15 06:38:18      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   ar   strong   for   

原题地址:http://oj.leetcode.com/problems/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.

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

解题思路:这题主要涉及到链表的节本操作。加一个头结点,操作起来会很方便。另外配了一个示意图 [本图是我asrman原创]

bubuko.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):
        pre = ListNode(0)
        pre.next = head
        curr = head
        head = pre
        while curr and curr.next:      # curr =1, curr.next =2
            pre.next = curr.next       # 0 --> 2
            curr.next = pre.next.next  # 1 --> 3  # curr.next.next
            pre.next.next = curr       # 3 --> 1
            pre = curr                 # pre = 1
            curr = curr.next           # curr= 3
        return head.next

参考:

https://oj.leetcode.com/discuss/3608/seeking-for-a-better-solution

[leetcode]Swap Nodes in Pairs @ Python

标签:des   style   blog   http   color   io   ar   strong   for   

原文地址:http://www.cnblogs.com/asrman/p/3972094.html

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