这个题比较简单我写的思路也是很容易理解的思路,就是说先去找到尾结点,并在这个过程中不断的入栈.
后面就是去释放他们,head和tail相等 或者 tail.next=head的时候就是循环该结束的时候
不过说实话,我这玩意只是改了下数据
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head:
return head
#建栈
stack=[]
#先循环一边该入栈的入栈
tail=head
while tail.next:
#入栈
stack.append(tail)
#后移
tail=tail.next
#再次进行循环换元素
t=head
while t!=tail and tail.next!=t:
t.val,tail.val=tail.val,t.val
t=t.next
tail=stack.pop()
return head
再来一个
def reverse(head):
if not head:
return head
#快乐的第一步还是从建栈开始
stack=[]
#循环找到尾结点
tail=head
while tail.next:
stack.append(tail)
tail=tail.next
t=tail
#现在就不停的出栈就好了
while stack:
p=stack.pop()
t.next=p
t=p
return tail
c=ListNode()
tail=c
for i in range(1,5):
p=ListNode(i)
tail.next=p
tail=p
head=reverse(c)
while head:
print(head.val)
head=head.next
吐了啊,就这个代码给我搞了半天,气死我了.
问题就是如果你要打印的话,她会出现最开始的第一位和第二位的死循环,比如上面的代码就会一直循环10101010101010101…就是因为0的next是指向1的,就导致了他俩一直互相py
改一下之后
def reverse(head):
if not head:
return head
#快乐的第一步还是从建栈开始
stack=[]
#循环找到尾结点
tail=head
while tail.next:
stack.append(tail)
tail=tail.next
t=tail
#现在就不停的出栈就好了
while stack:
p=stack.pop()
t.next=p
t=p
t.next=None
return tail
c=ListNode()
tail=c
for i in range(1,5):
p=ListNode(i)
tail.next=p
tail=p
head=reverse(c)
while head:
print(head.val)
head=head.next
其实这个还没有第一个写的好,就时间复杂度而言,所以有没有什么办法将第一种方法改进一下???
当然是有的那就是在往后找尾结点的同时,把链表顺序往后调一下
下面就是具体的代码实现,注释写的我已经能看懂了
说到注释不得不说,好玩意
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head:
return head
#这种写法是不需要建栈的写法
#主要是设置parent current next 这三个变量来不断地向后移动
parent=None
current=head #先初始化好这三个变量
next=current.next
while current.next:
#第一步 当前节点连parent
current.next=parent
#第二步 parent 后移
parent=current
#第三步 当前节点后移
current = next
#第四步 next后移
next=current.next
#出来的时候current是尾结点,但他未与上一个节点相连
current.next=parent
return current