• javascript数据结构-链表


    gihtub博客地址

    链表 是一种物理存储单元上非连续、非顺序的存储结构,它既可以表示线性结构,也可以用于表示非线性结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。

    function LinkedList() {
    	function Node(element) {
    		this.element = element;
    		this.next = null;
    	}
    	var length = 0;
    	var head = null;
    	this.append = function(element) {
    		var node = new Node(element);
    		if (!head) {
    			head = node;
    		} else {
    			var current = head;
    			while (current.next) {
    				current = current.next;
    			}
    			current.next = node;
    		}
    		length++;
    	};
    	this.insert = function(element, position) {
    		if(!position || !element){
    			return false;
    		}
    		var current = head,
    			previous = null,
    			index = 0;
    		var node = new Node(element);
    		if(position >= 0 && position <= length-1){
    			if(position == 0){
    				node.next = current;
    				head = node;
    			}else{
    				while(index++ < position){
    					previous = current;
    					current = current.next;
    				}
    				node.next = current;
    				previous.next = node;
    			}
    			length++;
    		}
    	};
    	this.removeAt = function(position) {
    		var current = head,
    			previous = null,
    			index = 0;
    		if(position >= 0 && position <= length-1){
    			if(position == 0){
    				head = current.next;
    			}else{
    				while(index++ < position){
    					previous = current;
    					current = current.next;
    				}
    				previous.next = current.next;
    			}
    			length--;
    			return current.element;
    		}
    	};
    	this.remove = function(element) {
    		var index = this.indexOf(element);
    		return this.removeAt(index);
    	};
    	this.indexOf = function(element) {
    		var current = head,
    			index = 0;
    		while(current){
    			if(element == current.element){
    				return index;
    			}
    			index++;
    			current = current.next;
    		}
    		return -1;
    	};
    	this.isEmpty = function() {
    		return length == 0;
    	};
    	this.size = function() {
    		return length;
    	};
    	this.getHead = function() {
    		return head.element;
    	};
    	this.toString = function() {
    		var current = head;
    		var s = "";
    		while(current){
    			s += (","+current.element);
    			current = current.next;
    		}
    		return s.substr(1);
    	};
    	this.print = function() {
    		console.log(this.toString())
    	};
    }
    

      

  • 相关阅读:
    腾讯分析系统架构解析
    GreenPlum简单性能测试与分析--续
    我的一些提高效率的设置
    Windows 上借助注册表来修改键盘按键的映射
    WPF入门——Converter、XAML和Style
    30个极大提高开发效率的Visual Studio Code插件(转)
    USB PD充电
    macOS Mojave 美化一下终端
    WPF入门(4)——资源
    使用Duilib开发Windows软件(5)——使用VLC做视频播放
  • 原文地址:https://www.cnblogs.com/donglegend/p/6043443.html
Copyright © 2020-2023  润新知