单链表添加节点

image.png

  1. function insert(head,val){
  2. const newNode = listNode(9)
  3. const cur = head
  4. while(head.next && !cur === val){
  5. cur = head.next
  6. }
  7. const next = cur.next
  8. newNode.next = next
  9. cur.next = newNode
  10. return head
  11. }

在链表头部添加

  1. const newNode = listNode(0)
  2. newNode.next = head
  3. head = newNode
  4. return head

在链表尾部添加

  1. while(head.next){
  2. // 移动 head 指针
  3. head = head.next;
  4. }
  5. // 新节点插入尾部
  6. head.next = newNode;

单链表删除节点

image.png

  1. function deleteNode(head, val){
  2. if(head === null) return
  3. let prev = null
  4. let cur = head
  5. while(head.next && cur !== val){
  6. prev = cur
  7. cur = head.next
  8. }
  9. prev.next = cur.next
  10. return head
  11. }