链表的转换与创建
-链表操作
-前插
-后插
-查询
-插入
function LinkNode(value,next){
this.value=value;
this.next=next|null;
}
function createLinkList2(arr){
//定义一个头节点
let head=new LinkNode(0);
let tmp =head;
for(const item of arr){
let node =new LinkNode(item);
tmp.next =node;
tmp=node;
}
return head.next;
}
/**
* @param{新节点的值}value
* @param{链表的头节点}oldhead
*
*/
function prepend(value,oldhead){
let node =new LinkNode(value);
node.next=oldhead;
return node;
}
function getLastNode(head){
let tmp = head;
//节点的下一个节点为Null的时候,说明就是最后一个节点
while(tmp.next){
tmp=tmp.next;
console.log(tmp)
}
return tmp ;
}
/**
* 将一个元素追加到链表的最后节点
* @param{any}val
* @param{*}head
*/
function append(val,head){
if(!head)return new LinkNode(val);
let node= new LinkNode(val);
let lastNode =getLastNode(head);
lastNode.next= node;
return head;
}
function printNode(linkNode){
let tmp =linkNode;
while(tmp){
console.log("link Node Data:"+tmp.value);
tmp=tmp.next;
}
}
function findNode(ele,head){
if(!head) return null ;
let tmp = head;
while(tmp){
if(tmp.value===ele){
return tmp;
}
tmp=tmp.next;
}
return null;
}
//通过索引来找节点
function findIndex(index,head){
if(!head)return null;
let tmp = head;
let i=0;
while((i<index)&&tmp){
i++;
tmp=tmp.next;
}
if(tmp&&(i===index)){
return tmp;
}else{
return null;
}
}
let array=[100,200,300,400,500,600];
let head_node=createLinkList2(array);
//head_node=prepend(111,head_node);
let fnode=findNode(400,head_node);
console.log(fnode)//LinkNode {value: 400, next: LinkNode}
let ffnode =findIndex(5,head_node);
console.log(ffnode);//LinkNode {value: 600, next: 0}
//append(700,head_node);
//printNode(head_node);