删除链表中第K个节点

首先这个问题要找到链表中第K个节点;

步骤:

1.定义一个快指针和慢指针分别指向链表的头节点;

2.让快指针向右走动K个节点,慢指针在原地不动;

3.同时移动快指针和慢指针,指导快指针的next域的值为空;

4.那么慢指针指向的就是倒数第k个元素;

5.存储慢指针的前驱节点,然后直接删除慢指针指向的节点;

 // 删除倒数第K个结点
  public static Node deleteLastK(Node list, int k) {
    Node fast = list;
    int i = 1;
    while (fast != null && i < k) {
      fast = fast.next;
      ++i;
    }

    if (fast == null) return list;

    Node slow = list;
    Node prev = null;
    while (fast.next != null) {
      fast = fast.next;
      prev = slow;
      slow = slow.next;
    }

    if (prev == null) {
      list = list.next;
    } else {
      prev.next = prev.next.next;
    }
    return list;
  }

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/82984093