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

链表问题(3)-----反转

时间:2018-10-01 12:24:26      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:ret   ini   空间复杂度   none   value   额外   list   self   bsp   

1、题目:反转单链表或双链表

要求:如果链表长度为N,时间复杂度为O(N),额外的空间复杂度为O(1)

反转单链表的思路:

1 → 2 → 3 → 4 → 5

(1)first = head = 1  

循环:

   temp = head.next   2

        head.next = temp.next   1 → 3

        temp.next = first    2 →1

        first = temp            2    【此时的头结点是2】

代码:

class Node:
    def __init__(self,value):
        self.value = value
        self.next = None
def reverseList(head):
    if not head:
        return head
    first = head
    while head.next:
        temp = head.next
        head.next = head.next.next
        temp.next = first
        first = temp
    return first
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
reverseList(head)

反转双链表的思路:

只要将每个节点的 next 和 last 互换就可以了。

代码:

class Node:
    def __init__(self,value):
        self.value = value
        self.next = None
def reverseList(head):
    if not head:
        return head

#重点
    while head:
        head.next , head.last = head.last,head.next
        head = head.last
    return head


head = Node(1)
head.last = None
head.next = Node(2)
head.next.last = head
head.next.next = Node(3)
head.next.next.last = head.next
head.next.next.next = Node(4)
head.next.next.next.last = head.next.next
head.next.next.next.next = Node(5)
head.next.next.next.next.last =  head.next.next.next
reverseList(head)

 

链表问题(3)-----反转

标签:ret   ini   空间复杂度   none   value   额外   list   self   bsp   

原文地址:https://www.cnblogs.com/Lee-yl/p/9734407.html

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