Lintcode-easy-remove Linked List Elements

Source: Internet
Author: User
Tags lintcode

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.