[LeetCode] 203. Remove Linked List Elements, leetcode203.remove

Source: Internet
Author: User

[LeetCode] 203. Remove Linked List Elements, leetcode203.remove

Question

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

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

Ideas

Delete A linked list node.

Code

/* ------------------------------------- * Date: * Author: SJF0115 * Subject: 203. remove Linked List Elements * URL: Login result: AC * Source: LeetCode * blog: ------------------------------------------- */# include <iostream> # include <vector> using namespace std; struct ListNode {int val; ListNode * next; ListNode (int x): val (x), next (nullptr) {}}; class Solution {public: listNode * removeElements (ListNode * head, int val) {if (head = nullptr) {return nullptr;} // if ListNode * dummy = new ListNode (0 ); dummy-> next = head; ListNode * pre = dummy; ListNode * cur = head; ListNode * tmp; while (cur) {if (cur-> val = val) {tmp = cur; pre-> next = cur-> next; delete tmp; cur = pre-> next;} // if else {pre = cur; cur = cur-> next;} // else} // while return dummy-> next ;}}; int main () {Solution solution; listNode * head = new ListNode (1); ListNode * node1 = new ListNode (5); ListNode * node2 = new ListNode (2); ListNode * node3 = new ListNode (1 ); listNode * node4 = new ListNode (4); ListNode * node5 = new ListNode (1); head-> next = node1; node1-> next = node2; node2-> next = node3; node3-> next = node4; node4-> next = node5; head = solution. removeElements (head, 6); while (head) {cout 

Running time

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.