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 移除之。

相关文章:

  • 2021-09-15
  • 2022-02-16
  • 2022-02-24
  • 2021-11-15
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-26
  • 2021-09-07
  • 2021-10-27
  • 2021-11-14
  • 2021-07-11
  • 2022-02-24
相关资源
相似解决方案