题解 | #翻转链表#

翻转链表

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))


    
    



全部评论

相关推荐

09-24 18:30
已编辑
长春工业大学 产品经理
小肥罗:HR就是好人的缩写哈哈哈哈
点赞 评论 收藏
分享
叁六玖:不买课还想秋招
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务