新博文地址:[leetcode]Remove Nth Node From End of List
http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
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.
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.
虽然提示n始终合法,但是还是画蛇添足验证了一下:
边界情况有两种:
list == null
listLength=n【n = 1本来是特殊的,但是可以跟一般情况合并】
代码如下:
public ListNode removeNthFromEnd(ListNode head, int n) {
int length = getLength(head);
if(head == null || n > length){
return null;
}
if(length == n){
return head.next;
}
ListNode tem1 = head;
ListNode tem2 = head;
//find the N+1th node from the end of list -- tem2's preNode
for(int i = 0 ; i < length; i++){
tem1 = tem1.next;
if(i > n){
tem2 = tem2.next;
}
if(tem1 == null){
break;
}
}
tem2.next = tem2.next.next;
return head;
}
private int getLength(ListNode head){
int length = 0;
while(head != null){
head = head.next;
length++;
}
return length;
}