《单链表》

91 阅读1分钟

主要操作:

  • 创建一个结点
  • 在链表尾部增加一个结点
  • 删除链表中指定结点
  • 遍历整个链表
const createNode = value => {
  return {
    data: value,
    next: null
  };
};

//创建只有一个结点的链表
const createList = value => {
  return createNode(value);
};

//在一个链表后边连接新的结点,并且返回新结点
const appendList = (list, value) => {
  const node = createNode(value);
  let cur = list;
  while (cur.next) {
    cur = cur.next;
  }
  cur.next = node;
  return node;
};

//从一个链表中删除一个结点
const removeNode = (list, node) => {
  //debugger;
  let cur = list;
  let pre = null;
  while (cur !== node && cur) {
    pre = cur;
    cur = cur.next;
  }
  if (!cur) {
    console.log("你要删除的结点不存在");
  } else {
    pre.next = cur.next;
    return list;
  }
};

//遍历链表中所有结点,对每个结点进行fn操作
const travelList = (list, fn) => {
  let cur = list;
  while (cur) {
    fn(cur);
    cur = cur.next;
  }
};

const list1 = createList(10);
const node2 = appendList(list1, 20);
const node3 = appendList(list1, 30);

const list2 = removeNode(list1, node4);

travelList(list1, x => console.log(x.data));
//console.log("新的list2");
//console.log(list2);