节点

节点是链表中的基本最小单元,由两个基本属性组成,data是数据,next为指向。

  1. function Node(){
  2. this.data = data;
  3. this.next = null;
  4. }

有头链表,无头链表

指的是头部是否存放数据,图解如下:

image.png

代码实现

基本结构

  1. function LinkList(){
  2. function Node(data){
  3. this.data = data;
  4. this.next = null
  5. }
  6. let length = 0;
  7. let head = null;
  8. let tail = null;
  9. //链表尾部加入数据
  10. this.append = function(data){
  11. let newNode = new Node(data);
  12. if(head === null){
  13. head = newNode
  14. tail = newNode;
  15. }else{
  16. tail.next = newNode;
  17. tail = newNode;
  18. }
  19. length +=1;
  20. }
  21. //打印节点数据 遍历链表
  22. this.print = function(){
  23. let currentNode = head;
  24. while(currentNode){
  25. console.log(currentNode.data);
  26. currentNode = currentNode.next
  27. }
  28. }
  29. }

insert插入方法

image.png

  1. // 指定位置加入一个元素
  2. this.insert = funnction(index,data){
  3. if(index < 0 || index > length){
  4. return false;
  5. }
  6. if(index === length){
  7. this.append(data);
  8. } else {
  9. let newNode = new Node(data);
  10. if(index === 0 ){
  11. newNode.next = head;
  12. head = newNode;
  13. } else {
  14. let currentNode = head;
  15. let currentIndex = 1;
  16. while(currentIndex < index){
  17. currentIndex += 1;
  18. currentNode = currentNode.next;
  19. }
  20. newNode.next = currentNode.next;
  21. currentNode.next = newNode;
  22. }
  23. }
  24. length += 1
  25. }

指定位置删除一个元素

与增加逻辑差不多,这里只重点理解循环部分的逻辑

  1. // 指定位置一个元素
  2. this.remove = funnction(index){
  3. if(index < 0 || index > length){
  4. return false;
  5. }
  6. if(index === length){
  7. this.pop(length);
  8. } else {
  9. let newNode = new Node(data);
  10. if(index === 0 ){
  11. head = head.next;
  12. } else {
  13. let currentNode = head;
  14. let currentIndex = 1;
  15. while(currentIndex < index){
  16. currentIndex += 1;
  17. currentNode = currentNode.next;
  18. }
  19. currentNode.next = currentNode.next.next;
  20. }
  21. }
  22. length--
  23. }