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.逆序链表,时间开销貌似较大,而且也很麻烦,和扫描两次链表没啥区别,不做
2. 观察,如果放两个指针,p 和q,如果q指向链表尾,p指向第n个节点的话(反向数节点),那么刚好,也就是说保证p和q指针的距离,扫描链表,等q到链表尾了,p也就是指向了想要remove的节点了
特殊情况就是如果要删的是head节点(原因在于p,q初始都从head开始)
另外要注意的是删节点需要知道前驱,所以遍历到待删除节点的前驱就不要再扫描了
1 public ListNode removeNthFromEnd(ListNode head, int n) { 2 ListNode p = head; 3 ListNode q = head; 4 5 //Init to make sure the distance between p and q is (1,n) 6 int counter = 1; 7 while(counter < n){ 8 q = q.next; 9 counter ++; 10 } 11 12 //if n points to the head 13 if(q.next == null){ 14 return head.next; 15 } 16 17 //remove a node needs to know its previous node 18 while(q.next.next !=null){ 19 p = p.next; 20 q = q.next; 21 } 22 //remove the node 23 p.next = p.next.next; 24 25 return head; 26 27 }