4.17 链表的前后节点操作

链表的转换与创建

 -链表操作

   -前插

   -后插

   -查询

   -插入

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值