LeetCode Online Judge 题目C# 练习 - Remove Nth Node From End of List

本文介绍了如何通过一次遍历来删除链表中的倒数第N个节点,包括代码实现和详细解释。

Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.

 1         public static LinkedListNode RemoveNthNodeFromEndofList(LinkedListNode head, int n)
 2         {
 3 
 4             LinkedListNode p = head;
 5             LinkedListNode q = head;
 6 
 7             for (int i = 0; i < n; i++)
 8             {
 9                 //if p == null mean the node to be remove is head node
10                 if (p == null)
11                     return head.Next;
12                 p = p.Next;
13             }
14 
15             while (p != null)
16             {
17                 p = p.Next;
18                 q = q.Next;
19             }
20 
21             //remove the q.next;
22             q.Next = q.Next.Next;
23 
24             return head;
25         }

代码分析:

  做两指针,p, q(q将指向要remove的前一个node)。p先走 n + 1 步,如果p 走到尾了 (p == null), 那证明所要移除的是head node, 那直接返回head.next搞定。然后p, q一起往前走,让p走到底, 那么这时候q.next就是要移除的node。 q.next = q.next.next 移除之。

转载于:https://www.cnblogs.com/etcow/archive/2012/10/12/2721947.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值