题目描述
例如:
输入:a->b->c->d->e
输出:a<-b<-c<-d<-e
反转链表示意图如下,链表的最后一个元素next指向null。
链表示意图" class="has" src="https://img-blog.csdnimg.cn/20190408161404713.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzI3OTU0NjQz,size_16,color_FFFFFF,t_70" />
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function isEmptyObject(obj) {// 判断输入参数链表是否为空
for (var name in obj) {
return false;
}
return true;
}
function ReverseList(pHead) {
if (isEmptyObject(pHead)) {// 调用链表是否为空函数
return false;
}
var pre = null;//链表的最后一个元素
var next = null;//初始化next为null,下面再赋值
while (pHead != null) {//pHead移动,直至到链表最后一个元素,指向null,结束循环
next = pHead.next;//pHead.next值先赋给next,以免覆盖,next移动
pHead.next = pre;//改变pHead指向,给pHead.next赋值,指向null
pre = pHead;//pre移动
pHead = next;//pHead移动
}
return pre;
}
这是前端面试考察链表的基本题型,需要理解和掌握。