定义
链表是一组节点组成的结合!
特点:
-
每个节点都使用一个对象引用指向它的后继,而这个引用就叫做链!
-
链表最后一个节点总是指向null节点!
-
链表有一个虚拟的头节点(head)作为链表的接入点!
-
链表的循环需要从首元素到尾元素!
优点:插入节点和移除节点的数据处理最优(因为它不像数组每次的插入和移除都需要重新移动位置)
分类
单向链表
graph TD
head --> first --> second -->third --> null
解释:
head.next = first;
first.next = second;
//节点
function Node(ele){
this.ele = ele;
this.next = null;
}
//链表
function List(){
this.head = new Node("head");
}
双向链表
graph TD
head --> first --> second -->third --> null
third --> second --> first -->head --> null
head.next = first;
first.next = second;
head.pre = null;
first.pre = head;
//节点
function Node(ele){
this.ele = ele;
this.next = null;
this.pre = null;
}
//链表
function List(){
this.head = new Node("head");
}
解题:反转一个单链表
当前: 5 -> 4 -> 3 -> 2 -> 1 -> null
结果: null <-5 <- 4 <- 3 <- 2 <-1
解题思路:
思路: null 5 -> 4 -> 3 -> 2 -> 1 -> null,已知 head = 5
实际是将每个节点的next改变指向;
每次改变了next指向后会丢失上次的指向,可以先存储上次的指向再改变next的指向;
声明pre ,cur 这个两个变量,pre=null,cur=head,cur和pre还需要根据遍历改变不断改变值;
function reverse(head){
var pre = null
var cur = head
while(cur != null ){
var next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre //这里遍历最后,cur已为null,pre已为链表最后的一个值
}