當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
【javascript】数据结构-链表
生活随笔
收集整理的這篇文章主要介紹了
【javascript】数据结构-链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// 創建一個鏈表
function LinkedList(){// 創建一個Node輔助類,表示需要加入列表的項,它包含一個element屬性,即表示需要加入到列表中的值,next屬性表示指向下一個節點項目的指針let Node = function(element){this.element = element;this.next = null;};// 長度初始化為0,列表頭部初始化為空let length = 0;let head = null;// append方法,向鏈表尾部追加元素this.append = function(element){let node = new Node(element),current;// 列表中的第一個節點if(head == null){head = node;}else{current = head;// 循環列表,直到找到最后一項while(current.next){current = current.next;}// 找到最后一項,將next值賦給node,建立鏈接current.next = node;}// 更新列表長度length++;};// insert方法,向列表的特定位置插入一個新的項this.insert = function(position, element){// 檢查越界值if(position >=0 && position <=length){// current是對插入元素之后的元素的引用,previous是對插入元素之前的元素的引用let node = new Node(element),current = head,previous,index = 0;// 在第一項位置添加if(position === 0){node.next = current;head = node;}else{while(index++ < position){previous = current;current = current.next;}node.next = current;previous.next =node;}// 更新列表長度length++;return true;}else{return false;}};// removeAt方法:從鏈表特定位置移除一項this.removeAt = function(position){// 檢查越界值if(position > -1 && position < length){let current = head,previous,index = 0;// 移除第一項if(position === 0){head = current.next;}else{while(index++ < position){previous = current;current = current.next;}// 將previous與current的下一項鏈接起來,跳過current從而移除它previous.next = current.next;}// 更新列表長度length--;return current.element;}else{return null;}};// remove方法:從列表中移除一項this.remove = function(element){let index = this.indexOf(element);// 調用removeAt()方法return this.removeAt(index);};// indexOf方法:返回元素在列表中的索引,如果沒有該元素則返回-1;this.indexOf = function(element){let current = head,index = 0;while(current){if(element === current.element){return index;}index++;current = current.next;}return -1;};// isEmpty方法,如果鏈表中不包含任何元素,則返回true,否則返回falsethis.isEmpty = function(){return length === 0;};// size方法,返回鏈表中包含的元素個數,與數組的length屬性類似this.size = function(){return length;};// getHead方法:返回鏈表第一個元素this.getHead = function(){return head;};// toSting方法,由于鏈表使用了Node類,重寫了javascript的toString方法,讓其只輸出元素的值this.toString = function(){let current = head,string = '';while(current){string += current.element + (current.next ? ',':'');current = current.next;}return string;};// print方法,用于在控制臺輸出鏈表元素this.print = function(){console.log(this.toString());};
}// 鏈表的使用
var lnkst = new LinkedList();// 打印鏈表長度
console.log(lnkst.size());// 給鏈表添加元素
lnkst.append(1);
lnkst.append(2);
lnkst.append(3);
lnkst.append(4);
lnkst.append(5);// 調用打印方法
lnkst.print(); //輸出1,2,3,4,5// 插入元素
lnkst.insert(2,'a');
lnkst.print(); //輸出1,2,a,3,4,5// 按位置刪除元素
lnkst.removeAt(2);
lnkst.print(); //輸出1,2,3,4,5// 按值刪除元素
lnkst.remove(5);
lnkst.print(); //輸出1,2,3,4//判斷是否為空
console.log(lnkst.isEmpty()); //false// 獲取頭部;
console.log(lnkst.getHead()); //1
轉載于:https://www.cnblogs.com/dragonir/p/7705005.html
總結
以上是生活随笔為你收集整理的【javascript】数据结构-链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Hive性能调优
- 下一篇: Database 2 Day DBA g