Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
分析:
给一个链表和一个数字n,删除倒数第n个结点之后,返回这个链表的头结点。
方法一:
最容易想到的方法是先遍历整个链表,求得链表长度,然后再删除倒数第n个结点。但是这个方法需要遍历两次。
方法二:使用双指针,可以一次遍历完成删除操作。
使用虚拟头结点可以很方便的解决头结点为空的情况,定义两个指针p,q先都指向虚拟头结点,先把q往后走n+1次,然后p,q同步向后走,当q为NULL时,p所指向的结点的下一结点即为需要删除的结点。
Java:
class Solution {
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyHead = new ListNode();
dummyHead.next = head;
ListNode p = dummyHead, q = dummyHead;
for (int i = 0; i <= n; i++) {
q = q.next;
}
while (q != null) {
p = p.next;
q = q.next;
}
p.next = p.next.next;
return dummyHead.next;
}
}