leetcode_203 title--remove Linked list Elements (linked list)

Source: Internet
Author: User

Remove Linked List ElementsTotal accepted:8053 Total submissions:29898my submissions QuestionSolution

Remove all elements from a linked list of integers, that has value val.

Example
Given: 1---2--and 6---3---4---5, val = 6
Return: 1--2--and 3--4--5

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

Hide TagsLinked ListHas you met this question in a real interview? Yes No

Discuss

The problem is that by removing the points in the list that are the same as the given Val value, you remove the nodes in the list, which is likely to remove three (the head node, the middle node, the tail node)

So I only consider the problem of the head node in the first while loop, then the three pointer ptr1,ptr2 points to the current front and back, and PTR points to the current node.

#include <iostream>using namespace std;//definition for singly-linked list.struct listnode {int val; ListNode *next;    ListNode (int x): Val (x), Next (NULL) {}}; listnode* removeelements (listnode* head, int val) {listnode* ptr0=head; listnode* Ptr=head; listnode* Ptr1=head; listnode* ptr2=head;if (Head==null) return Head;while (1) {if (ptr0->val!=val) {if (ptr0->next==null) return ptr0; Ptr1=ptr0;ptr=ptr0->next;break;} Else{ptr=ptr0->next;free (PTR0); if (ptr==null) return ptr;elseptr0=ptr;}} Ptr1=ptr0;ptr=ptr0->next;while (1) {if (ptr->next==null) {if (ptr->val==val) {ptr1->next=null;free (PTR); return PTR0;} Elsereturn Ptr0;} Else{ptr2=ptr->next;if (ptr->val==val) {ptr1->next=ptr2;free (PTR);p tr=ptr2;ptr2=ptr->next;} Else{ptr1=ptr1->next;ptr=ptr->next;ptr2=ptr2->next;}}} return PTR0;} int main () {}

  

leetcode_203 title--remove Linked list Elements (linked list)

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.