单链表的基本结构
function Node(val,next){ this.val = val; this.next = next || null; }
1.链表的创建
a.尾插法,就是正常的尾部顺序插入,从数组创建链表
function tailCreateList(aSrc){ var head = new Node(); pHead = head; aSrc.forEach((item) => { var node = new Node(item); pHead.next = node; pHead = node; }) return head; }
b.头插法,将后面的数据插入到头部,头结点后面,形成倒序的列表
function headCreateList(aSrc){ var head = new Node(); pHead = head; aSrc.forEach((item) => { var node = new Node(item); node.next = pHead.next; pHead.next = node; }) return head; }
2.链表的遍历
function traverse(head,fVisit){ if(head == null){ return; } var cur = head.next; while(cur){ fVisit && fVisit(cur); cur = cur.next; } }
3.链表的查找
function find(head,val){ if(head == null){ return; } var cur = head; while(cur && cur.val != val){ cur = cur.next; } return cur; }
4.链表的插入
function insert(head,val,newVal){ if(head == null){ return; } var cur = head; while(cur && cur.val != val){ cur = cur.next; } if(cur){ var newNode = new Node(newVal); newNode.next = cur.next; cur.next = newNode; } }