剑指offer 66道-python+JavaScript
反转链表
时间限制: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;
}