链表操作-leetcode23-删除倒数第几个节点

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

示例 1:

img

示例 2:

输入:head = [1], n = 1
输出:[]

示例 3:

输入:head = [1,2], n = 1
输出:[1]

提示:

  • 链表中结点的数目为 sz
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz
思路:首先遍历所有节点计算总数,然后计算出要跳过的那个节点的前一个节点,然后利用探测指针跳过,由于要跳过的可能是头结点,所以需要假如一个探测节点,所以计算位置的时候 int position = len - n+1 -1+1;//要删除的节点的前一个节点,因为添加了一个虚节点,所以在+1 
需要这样结算
//leetcode submit region begin(Prohibit modification and deletion)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }

        int len = 0;
        ListNode dummy = head;
        while (dummy != null) {
            len++;
            dummy = dummy.next;
        }

        int position = len - n+1 -1+1;//要删除的节点的前一个节点,因为添加了一个虚节点,所以在+1
        System.out.println("position: " + position);

        int currPosition = 0;
        ListNode dummy3 = new ListNode(-1);
        dummy3.next = head;
        ListNode dummy2 = dummy3;

        while (dummy2 != null) {
            currPosition++;
            System.out.println("currPosition: " + currPosition);

            if (currPosition == position) {
                System.out.println("dummy2.next: "+dummy2.next.val);
                //System.out.println("dummy2.next.next: "+dummy2.next.next.val);

                dummy2.next = dummy2.next.next;


                return dummy3.next;
            } else {
                dummy2 = dummy2.next;
            }

        }
        return null;

    }
}
//leetcode submit region end(Prohibit modification and deletion)

posted @ 2023-03-22 10:50  小傻孩丶儿  阅读(18)  评论(0编辑  收藏  举报