标签:des style blog color io java strong for 数据
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.
初始版本:
1 public ListNode removeNthFromEnd(ListNode head, int n) { 2 if (n <= 0||head == null) { 3 return null; 4 } 5 ListNode nth = head; 6 ListNode des = head; 7 for(int i = 0;i < n;i++){ 8 if (des == null) { 9 return null; 10 } 11 des = des.next; 12 } 13 while(des.next!= null){ 14 nth = nth.next; 15 des = des.next; 16 } 17 18 nth.next = nth.next.next; 19 20 return head; 21 22 }
在本地自己定义了一个singleLinkedList,作为参数传进函数中,本地运行正确,可是在OJ上死活就是java.lang.NullPointerException,无奈一步步提交就是各种错误,而本地运行完全正确。后来照着答案一步步找原因才发现,当输入数据为{1},1或者{1,2},2时非常容易出现空指针的情况。因此无论如何,链表中保持有一个头指针(空指针,beginMaker)是一个非常明智的选择,将即使是一个数据也能像一般情况一样不容易出现错误。
修改后版本:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode removeNthFromEnd(ListNode head, int n) { 14 if (n <= 0||head == null) { 15 return null; 16 } 17 ListNode tmp = new ListNode(0); 18 tmp.next = head; 19 ListNode nth = tmp; 20 ListNode des = head; 21 22 for(int i = 0;i < n;i++){ 23 if (des == null) { 24 return null; 25 } 26 des = des.next; 27 } 28 while(des != null){ 29 nth = nth.next; 30 des = des.next; 31 } 32 33 nth.next = nth.next.next; 34 35 return tmp.next; 36 37 } 38 }
标签:des style blog color io java strong for 数据
原文地址:http://www.cnblogs.com/LolaLiu/p/3982290.html