删除单向链表倒数第n个节点

// 删除倒数第n个节点
public void del(int n, ListNode node) {
    int length = 0; // 记录链表长度
    ListNode head = node; // 保存头节点
    while (node != null) {
        length++;
        node = node.next; // 移动指针
    }
    ListNode resNode;
    // 从前往后找
    int left = length - n - 1;
    while (left != 0) {
        System.out.print(head.val + "->");
        head = head.next;
        left--;
    }
    head.next = head.next.next; // 跨越待删除的指针,没有引用时待删除的节点被垃圾回收
    while (head != null) {
        System.out.print(head.val + "->");
        head = head.next;
    }
    System.out.print("null");
}

你可能感兴趣的:(datastruct,java)