题解 | #翻转链表#
翻转链表
https://www.nowcoder.com/practice/f350f14cd22c41aabfa7e54a1b8e8825
import sys
class ListNode:
def __init__(self,val=0,next=None):
self.val=val
self.next=next
def parse_input(slist):
if not slist:
return None
head=ListNode(slist[0])
curr=head
for value in slist[1:]:
curr.next=ListNode(value)
curr=curr.next
return head
def reverseList(head):
if not head or not head.next:
return head
slow,fast=head,head
while fast and fast.next:
slow=slow.next
fast=fast.next.next
prev,curr=None,slow.next
slow.next=None
while curr:
next_tmp=curr.next
curr.next=prev
prev=curr
curr=next_tmp
first,second=head,prev
while second:
tmp1,tmp2=first.next,second.next
first.next=second
second.next=tmp1
first,second=tmp1,tmp2
return head
s=list(map(int,input().strip().split(',')))
# print(s)
head=parse_input(s)
head=reverseList(head)
res=[]
while head:
res.append(str(head.val))
head=head.next
print(",".join(res))
查看13道真题和解析