欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

c# Leetcoede 19. 删除链表的倒数第N个节点(链表)

程序员文章站 2024-03-06 10:57:43
...
给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.

相关知识点请参考:https://blog.csdn.net/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没了目标值
    }
}