剑指offer 66道:反转链表

本文提供了一种解决链表反转问题的方法,使用Python和JavaScript两种语言实现,包括三个指针遍历、尾插法和递归三种算法。通过具体的代码示例,详细介绍了每种方法的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

反转链表

时间限制:1秒 空间限制:32768K 热度指数:454860

题目描述
输入一个链表,反转链表后,输出新链表的表头。

思路

分别用python和javascript实现,均实现三种方法:三个指针遍历、尾插法、递归。

github

python代码链接: https://github.com/seattlegirl/jianzhioffer/blob/master/reverse-linked-list.py.

题目代码(python)

#-*- coding:utf-8 -*-
class LNode:
    def __init__(self,x):
        self.val=x
        self.next=None


#法一:利用三个指针遍历
# 返回ListNode
def ReverseList1(pHead):
    # write code here
    if pHead==None:
        return pHead
    p=pHead
    q=None
    r=None
    while(p):
        q=p.next
        p.next=r
        r=p
        p=q
    return r

#法二:尾插法实现
# 返回ListNode
def ReverseList2(pHead):
    # write code here
    if pHead==None:
        return pHead
    p=pHead
    q=None
    r=p
    while(p.next!=None):
        q=p.next
        p.next=q.next
        q.next=r
        r=q
    return r

#法三:递归实现
# 返回ListNode
def ReverseList3(pHead):
    # write code here
    if pHead.next==None: #递归跳出条件
        return pHead
    newHead=ReverseList3(pHead.next)
    pHead.next.next=pHead
    pHead.next=None
    return newHead

if __name__ == "__main__":
    l1=LNode(3)
    l1.next=LNode(2)
    l1.next.next=LNode(1)
    l1.next.next.next=LNode(99)
    l=ReverseList3(l1)
    print(l.val,l.next.val,l.next.next.val,l.next.next.next.val)

github

JavaScript代码链接: https://github.com/seattlegirl/jianzhioffer/blob/master/reverse-linked-list.js.

题目代码(JavaScript)

function ListNode(x){
    this.val = x;
    this.next = null;
}


//法一:利用三个指针遍历
function ReverseList1(head){
    if(head===null){
        return head;
    }
    var p=head;
    var q=null;
    var r=null;
    while(p!=null){
        q=p.next;
        p.next=r;
        r=p;
        p=q;
    }
    return r;
}

//法二:尾插法
function ReverseList2(head){
    if(head==null){
        return head;
    }
    var p=head;
    var q=null;
    var r=p;
    while(p.next!=null){
        q=p.next;
        p.next=q.next;
        q.next=r;
        r=q;
    }
    return r;
}

//法三:递归
function ReverseList3(head){
    if(head.next==null){//递归跳出条件
        return head;
    }
    var newHead=ReverseList3(head.next);
    head.next.next=head;
    head.next=null;
    return newHead;
}

var l1=new ListNode(3);
l1.next=new ListNode(2);
l1.next.next=new ListNode(1);
l1.next.next.next=new ListNode(99);

var l2=ReverseList3(l1);

while(l2!=null){
    console.log(l2.val);
    l2=l2.next;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值