问题描述:
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.
原问题链接:https://leetcode.com/problems/remove-nth-node-from-end-of-list/
问题分析
这个问题相对来说比较简单。因为要删除链表中从后往前的第n个元素,所以需要用一个元素first的引用先往前n步,然后再用一个引用second跟着这个元素一步步到链表的最后。既然要删除这个倒数第n的元素,可以在第二个元素后面跟一个元素,相当于它的前置元素pre。这样在后面删除这个节点的时候只需要设置pre.next = second.next就可以。这里有几个需要判断和容易出错的地方在于,当head == null的情况,在前置元素first还没走n步就已经到链表末尾的情况。
在把上述情况都考虑在内很容易得到如下的代码:
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null || n < 1) return head;
ListNode first = head, second = head, pre = null;
for(int i = 0; i < n ; i ++) {
if(first == null) return head;
first = first.next;
}
while(first != null) {
first = first.next;
pre = second;
second = second.next;
}
if(second == head) return second.next;
pre.next = second.next;
return head;
}
}