Remove all elements from a linked list of integers, that has value val
.
Example
Given 1->2->3->3->4->5->3
, val = 3, you should return the list as1->2->4->5
It seems that the problem is not difficult, but there are some places to pay attention, it is said that the interview to do Bug-free
p = p.next; after execution, p is likely to be null, so check whether P is null in the loop condition.
In fact, before accessing a member of an object, it is important to check whether the object is null or else an exception will occur.
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution {/** * @paramhead a ListNode *@paramval an integer *@returna ListNode*/ PublicListNode removeelements (ListNode head,intval) { //Write Your code here if(Head = =NULL) returnHead; ListNode Fakehead=NewListNode (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; } returnFakehead.next; }}
Lintcode-easy-remove Linked List Elements