这是一道 中等难度 题。
题目来自:https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/
题目
给你一个链表,删除链表的倒数第n个结点,并且返回链表的头结点。
示例1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
输入:head = [1], n = 1
输出:[]
示例3:
输入:head = [1,2], n = 1
输出:[1]
提示:
-
链表中结点的数目为 sz
-
-
-
解法一:计算链表长度
01
Java 代码实现
/**
* 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 protect = new ListNode(0);
protect.next = head;
int total = 0;
while(head != null){
total++;
head = head.next;
}
int deleteIndex = total + 1 - n;
ListNode pre = protect;
for(int i = 1; i < deleteIndex; i++){
pre = pre.next;
}
pre.next = pre.next.next;
return protect.next;
}
}
02
Go 代码实现
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNthFromEnd(head *ListNode, n int) *ListNode {
// 保护节点
protect := &ListNode{0, head}
// 计算链表长度
total := 0
for head != nil {
total++
head = head.Next
}
// 被删除节点位置
deleteIndex := total + 1 - n
// 找到删除节点的前一个
pre := protect
for i := 1; i < deleteIndex; i++ {
pre = pre.Next
}
pre.Next = pre.Next.Next
return protect.Next
}
03
复杂度分析
解法二:双指针
要删除倒数第n个节点,我们需要找到倒数第n + 1个节点。在扫描一次的前提下, 我们可以使用双指针来解题:
01
Java 代码实现
/**
* 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 protect = new ListNode(0);
protect.next = head;
ListNode first = protect, second = protect;
for(int i = 1; i <= n + 1; i++){
second = second.next;
}
while(second != null){
second = second.next;
first = first.next;
}
first.next = first.next.next;
return protect.next;
}
}
02
Go 代码实现
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func removeNthFromEnd(head *ListNode, n int) *ListNode {
protect := &ListNode{0, head}
first, second := protect, protect
for i := 1; i <= n + 1; i++ {
second = second.Next
}
for second != nil {
second = second.Next
first = first.Next
}
first.Next = first.Next.Next
return protect.Next
}
03
复杂度分析
点个
原文始发于微信公众号(i余数):【算法题解】13. 删除链表的倒数第 N 个结点
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/193997.html