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

LeetCode算法题python解法:24. Swap Nodes in Pairs

时间:2018-09-26 17:18:36      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:class   无法   空间   nbsp   代码   特殊情况   amp   base   tco   


原题:

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:

  • Your algorithm should use only constant extra space.
  • You may not modify the values in the list‘s nodes, only nodes itself may be changed.

中文翻译:

给定链表,交换每两个相邻节点并返回其头部。

例:

给定1->2->3->4,您应该将列表作为2->1->4->3

注意:

  • 您的算法应该只使用恒定的额外空间。
  • 您可能无法修改列表节点中的值,只能更改节点本身。

解题思路:该题非常简单,给定链表两两对调然后重新链接,返回新链表的头部即可。将链表遍历添加到一个列表linklist中,然后利用索引进行两两对调,最后重新连接这个链表,然后linklist[0]

代码如下:

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
class Solution:
    def swapPairs(self, head):         #思路非常简单,把链表遍历出来放到列表里,然后再两两对调,在重新链接链表。
        linklist = []
        x, y = 0, 1

        while head != None:  #将链表遍历到一个linklist列表中
            linklist.append(head)
            head=head.next
        if len(linklist)<1:   #这里排除一下特殊情况,如果给的链表为空,则直接返回空值
            return linklist

        while y <= len(linklist)-1:      #这里进行两两对调
            linklist[x], linklist[y] = linklist[y], linklist[x]
            x, y = x + 2, y + 2

        for i in range(len(linklist)-1):        #将对调后的linklist链接成新的链表
            linklist[i].next=linklist[i+1]
        linklist[-1].next=None                   #设置链表最后一个值的末端为空值
        return linklist[0]

 

LeetCode算法题python解法:24. Swap Nodes in Pairs

标签:class   无法   空间   nbsp   代码   特殊情况   amp   base   tco   

原文地址:https://www.cnblogs.com/slarker/p/9707661.html

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