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)用p,q两个指针来记录2个位置,p,q初始化为head;
2)然后p先不动,q向后移动n个位置;
3)接着p,q以同样的步伐一起向链表尾部移动,直到q到达链表尾部,即q.next==null;
4)此时p是待删除节点的前驱,修改p.next即可。
这里一个细节要考虑,若n等于节点数,即删除倒数第n个也就是第1个节点,那么在第2)步q会移动到尾部节点下一个位置即q==null,所以移动时加个判断即可。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode p = head; ListNode q = head; while(n!=0){ q = q.next; //如果q==null说明n==List.length,即删除第一个节点 if(q==null){ return head.next; } n--; } while(q.next!=null){ p = p.next; q = q.next; } ListNode temp = p.next; p.next = temp.next; return head; } }