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.
解:先求链表的长度由此得出被删节点的位置,同时注意被删节点位于首尾的特殊情况,避免空指针错误。
/**
* 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) {
ListNode listNode = head;
ListNode temp = null;
int length = 0;
int position = 0;
//求整个长度
while(head!= null){
length++;
head = head.next;
}
//恢复head
head = listNode;
//待删除节点的位置
position = length - n;
if (position == 0){
return head.next;
}
while ((--position) > 0) {
head = head.next;
}//此时head指向待删除节点的前面的一个位置
if (n == 1){//防止空指针错误
head.next = null;
}else if (n>1) {
temp = head.next.next;
head.next = temp;
}
return listNode;
}
}
以上求被删节点的位置并不是最优,另一种较好的解法可参考:
http://blog.csdn.net/bigapplestar/article/details/12461793