给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
相关知识点请参考:https://blog.youkuaiyun.com/us2019/article/details/87941699
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
ListNode newnode = new ListNode(0);
newnode.next = head;
int count = 0;int index = 0;
while (head!=null)
{
count++;
head = head.next;
}
head = newnode;// 0 1 2 3 4 5
while (index<count-n)
{
head = head.next;
index++;
}
//head= 3 4 5 找到要删除的目标值的前一个为head;
if (head.next.next!=null)
{
head.next = head.next.next; // just do it (做了它)
}
else
{
head.next = null;
}
return newnode.next;//为什么newnode没了目标值
}
}

本文介绍了一种算法,用于从链表中删除倒数第N个节点,并通过一个具体示例进行了解释。例如,对于链表1->2->3->4->5和N=2,在删除倒数第二个节点后,链表变为1->2->3->5。该算法首先计算链表长度,然后再次遍历链表以定位并删除目标节点。
674

被折叠的 条评论
为什么被折叠?



