您的位置:首页 > 其它

lintcode-easy-Remove Linked List Elements

2016-02-18 13:06 351 查看
Remove all elements from a linked list of integers that have value
val
.

Example

Given
1->2->3->3->4->5->3
, val = 3, you should return the list as
1->2->4->5


看起来这题不难,但是还是有些地方需要注意,据说面试要做到bug-free

p = p.next;执行之后,p有可能是null,所以在循环条件中要检查p是否为null。

其实任何时候访问一个对象的成员之前,都要注意检查这个对象是否为null,否则会出现异常。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @param val an integer
* @return a ListNode
*/
public ListNode removeElements(ListNode head, int val) {
// Write your code here
if(head == null)
return head;

ListNode fakehead = new ListNode(0);
fakehead.next = head;

ListNode p = fakehead;

while(p!= null && p.next != null){
while(p.next != null && p.next.val == val){
p.next = p.next.next;
}

p = p.next;
}

return fakehead.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: