什么是双向链表?双向链表的操作封装实现(增删改查)?
-
既可以从头遍历到尾, 又可以从尾遍历到头
-
也就是链表相连的过程是双向的. 那么它的实现原理, 你能猜到吗?
-
一个节点既有向前连接的引用, 也有一个向后连接的引用.
-
双向链表的操作封装实现
// 节点的结构 只能通过newnode调用 class Dnode { constructor(data) { this.prev = null; this.data = data; this.next = null; } } // 链表的结构 class DoubleLinkList { constructor() { this.head = null; this.tail = null this.length = 0; } // 1、向链表最后添加元素 append(ele) { // 创建新节点 let newnode = new Dnode(ele); // console.log(newnode); // 当头节点为空 if (this.length == 0) { this.head = newnode; this.tail = newnode; } else { newnode.prev = this.tail this.tail.next = newnode; this.tail = newnode } this.length++ } // 2、向指定位置插入元素 insert(position, ele) { // 位置是否合法 if (position = 0 || position > this.length || !Number.isInteger(position)) { return false } let newnode = new Dnode(ele) // 1、在头部插入 if (position == 0) { if (this.length == 0) { this.head = newnode; this.tail = newnode; } else { newnode.next = this.head; this.head.prev = newnode this.head = newnode } this.length++; } else if (position == this.length) { //尾部 this.append(ele) } else { let current = this.head, index = 0 while (index < position - 1) { current = current.next; index++ } newnode.prev = current; newnode.next = current.next current.next = newnode; current.next.prev = newnode; this.length++ } } // 3、移除指定位置的元素 removeAt(position) { if (position < 0 || position > this.length - 1 || !Number.isInteger(position)) { return false } if (this.length == 0) { return } else { if (position == 0) { if (this.length == 1) { this.head = null this.tail = null } else { this.head = this.head.next this.head.prev = null } this.length--; } else if (position == this.length - 1) { this.tail = this.tail.prev this.tail.next = null } else { let current = this.head, index = 0 while (index < position - 1) { current = current.next; index++ } current.next = current.next.next current.next.prev = current } this.length-- } } // 4、查找指定元素的位置 indexOf() { let current = this.head, index = 0; while (index < this.length) { if (current.data == ele) { return index } else { //不相等时 current = current.next index++; } } return -1; } // 5、移动指定元素 remove(ele) { let index = this.indexOf(ele); this.removeAt(index) } // 6、正向遍历 toAfterString() { let current = this.head, index = 0; while (index < this.length) { res += "-" + current.data; current = current.next index++ } return res.slice(1) } // 7、反向遍历 toBeforeString() { let current = this.tail, index = this.length - 1; while (index < this.length) { res += "-" + current.data; current = current.next index++ } return res.slice(1) } } let dlist = new DoubleLinkList(); for (let i = 0; i < 5; i++) { list.append(i) } console.log(dlist);