LeetCode(中等)删除链表的倒数第N个节点(c#)

题目为 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.

这里要说明一下链表的结构,是如下结构,每个节点都指向下一个元素。

	public class ListNode
    {
      public int val;
      public ListNode next;
      public ListNode(int x) { val = x; }
    }

删除一个元素的意思就是让这个元素的上一个元素不再指向该元素,而是指向该元素的下一个元素,节点就从链表中删除了。删除B的意思如下所示图示
A——>B——>C 转换成A——>C

我的思路是使用递归,当元素没有子节点的时候,代表该元素已经到结尾末端,这时递归向上返回时,我们依次加1,也就是末尾最后一个元素返回1,倒数第二个元素返回1+1,依次类推,当返回值res等于我们要删除的倒数第n个节点减1的时候,就是删除元素的下一个元素。当等于n+1的时候,是删除元素的上一个元素。理解了思路,代码如下。

		public ListNode RemoveNthFromEnd(ListNode head, int n)
        {
            int all= GetDetailCount(head, n);
            if (all==n)
            {
                return head.next;
            }
            liBegin.next = liAfter;
            return head;
        }
	
        public ListNode liBegin = null;
        public ListNode liAfter = null;

        public int GetDetailCount(ListNode head,int n)
        {
            if (head.next == null)
            {
                if (1 == n - 1)
                {
                    liAfter = head;
                }
                else if (1 == n + 1)
                {
                    liBegin = head;
                }
                return 1;
            }
            else
            {
                int res = GetDetailCount(head.next, n) + 1;
                if (res==n-1)
                {
                    liAfter = head;
                }
                else if (res == n + 1)
                {
                    liBegin = head;
                }
                return res;
            }
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值