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

leetcode_024 Swap Nodes in Pairs

时间:2017-05-17 19:10:14      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:efi   one   nod   wap   ppa   leetcode   出错   pre   its   

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.


key:返回值出错,包括头结点

Python实现:

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

class Solution(object):
    def swapPairs(self, head):
        if head is None or head.next is 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

 

leetcode_024 Swap Nodes in Pairs

标签:efi   one   nod   wap   ppa   leetcode   出错   pre   its   

原文地址:http://www.cnblogs.com/ytq1016/p/6868907.html

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