[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