[LeedCode OJ] #203 Remove Linked List Elements,

Source: Internet
Author: User

[LeedCode OJ] #203 Remove Linked List Elements,

[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]


Link: https://leetcode.com/problems/remove-linked-list-elements/


Question:

Given a linked list and a number of x, it is required to delete all the nodes equal to x in the linked list and return the new linked list.


Ideas:

It's easy to directly traverse the entire linked list. Once the same node as x is found, it will be skipped directly. Be careful when dealing with several consecutive nodes that are equal to x.


/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution{public:ListNode* removeElements(ListNode* head, int val){while(head && head->val==val)head = head->next;ListNode *cur = head;ListNode *newlist = new ListNode(0);ListNode *ptr = newlist;while(cur){while(cur && cur->val == val)cur = cur->next;if(cur==nullptr)break;ListNode *pnext = cur->next;ptr->next = cur;cur = pnext;ptr = ptr->next;}ptr->next = nullptr;return newlist->next;}};


Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source

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.