zoukankan      html  css  js  c++  java
  • 单链表的尾插,头插,遍历,查找和插入

    单链表的基本结构

    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;
        }
    }
  • 相关阅读:
    SaltStack 配置SLS过程
    Python 正则表达式
    Python 矩阵的旋转
    SaltStack 远程执行
    SaltStack 配置管理
    SaltStack
    Python 装饰器
    Python 生产者和消费者模型
    Python 迭代器和生成器
    Python json模块
  • 原文地址:https://www.cnblogs.com/mengff/p/6876010.html
Copyright © 2011-2022 走看看