举例:head -> 1 ->2 ->3 ->4 ->5 ->null
1 //链表反转
2 var reverseList = function (head) {
3 //pre结点可以用来反转方向,为了避免反转之后链表断开
4 let pre = null;
5 while(head){
6 //先用next保存head的下一个结点信息,保证单链表不会断裂;
7 next = head.next;
8 //让head从指向next变成指向pre;
9 head.next = pre;
10 //到此,完成了pre到head的反转,即pre<--head;
11
12 //将pre,head,next依次向后移动一个结点。
13 pre = head;
14 head = next;
15 }
16 //如果head为null的时候,pre就为最后一个节点了,但是链表已经反转完毕,pre就是反转后链表的第一个节点
17 //直接输出pre就是我们想要得到的反转后的链表
18 return pre ;
}
链表定义
1 //链表:无法通过下标遍历,只能通过当前节点查找下一节点的链式结构
2
3 //构造链表节点
4 //this.val代表当前节点的值,this.next指向下一个节点,若this.next为null(对象),则说明该节点为链表的最后一个节点。
5 function Node(val) {
6 this.val = val;
7 this.next = null;
8 }
9
10 //定义链表
11 function list(arr) {
12 this.head = null;
13 var i,temp = null;
14 while(i < arr.length){
15 if(i === 0){
16 //头节点
17 this.head = new Node(arr[i]);
18 }else{
19 //
20 let newNode = new Node(arr[i]);
21 temp.next = newNode;
22 temp = temp.next;
23 }
24 i++;
25 }
26 }
原文:https://www.cnblogs.com/oaoa/p/14679356.html