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.
我觉得应该会有更简单的边界检查的办法。有待二刷修改。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null || head.next == null)
return null;
int count = 1;
ListNode p = head;
while(p.next != null){
count ++;
p = p.next;
}
if (count == n){
head = head.next;
return head;
}
else if (n == 1){
p = head;
for(int i = 0; i < count-n-1; i++){
p = p.next;
}
p.next = null;
return head;
}
else{
p = head;
for(int i = 0; i < count-n; i++){
p = p.next;
}
p.val = p.next.val;
p.next = p.next.next;
return head;
}
}
}