LeetCode Online Judge 题目C# 练习 - Remove Nth Node From End of List
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 移除之。