题目描述
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
思路
找到 List 一共有多少个 节点
通过 总节点 - 倒数节点数 + 1 得到 需要删除节点的位置
通过while 循环,循环到 该节点的前一个节点,直接跳过该节点,连接到下一个节点
拓展知识点,在对链表 操作的时候,
常用技巧: 添加一个 dummy node 哑铃点
next指针 是 指向 链表的头 节点
这样,就不用 对节点是否是头结点,进行特殊情况判断了。
为什么呢?
头结点 不存在 前驱节点,因此 需要在 删除头节点 时候 进行 特殊判断。
但是 如果 添加 哑铃节点,头结点 的前驱 就是哑铃节点,
通用就可以了。
代码
public class ListNode{
int val;
ListNode next;
ListNode(int val){
this.val = val;
}
ListNode(int val, ListNode next){
this.val = val;
this.next = next;
}
}
/**
* 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) {
int length = lengthList(head);
ListNode dummy = new ListNode(0,head);
ListNode cur = dummy;
for (int i = 1; i < length - n + 1; i++){
cur = cur.next;
}
cur.next = cur.next.next;
ListNode ans = dummy.next;
return ans;
}
public int lengthList(ListNode head){
if (head == null){
return 0;
}
int count = 1;
while (head.next != null){
count++;
head = head.next;
}
return count;
}
}
思路2
使用练个指针
但是同样得 创建 dummy 哑铃头结点
第一个节点first 指向 head
第二个节点second 指向 dummy
将 第一个指针 往后移动 n个位置
同时移动第一个 和 第二个 指针
知道 第一个指针为null
通过将第二个指针的next 跳过 下一个节点
second.next =second.next.next
返回
ListNnode ans = dummy.next
return ans
代码2
/**
* 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) {
ListNode dummy = new ListNode(0,head);
ListNode first = head;
ListNode second = dummy;
for (int i = 0; i < n; i++){
first = first.next;
}
while(first != null){
first = first.next;
second = second.next;
}
second.next = second.next.next;
ListNode ans = dummy.next;
return ans;
}
}
Reference
https://leetcode.cn/problems/remove-nth-node-from-end-of-list