-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path203.cpp
More file actions
78 lines (70 loc) · 1.86 KB
/
203.cpp
File metadata and controls
78 lines (70 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//
// 203.cpp
// LeetCode
//
// Created by 张佐玮 on 15/5/17.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: Remove Linked List Elements
//
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *front = new ListNode(0);
front -> next = head;
ListNode *pre = front, *current = head;
while (current != NULL) {
if (current -> val == val) {
pre -> next = current -> next;
delete current;
}
else {
pre = pre -> next;
}
current = pre -> next;
}
ListNode *result = front -> next;
delete front;
return result;
}
};
class Test {
private:
static ListNode *arrayToList(int input[], int length) {
if(length < 1)
return NULL;
ListNode *head = new ListNode(input[0]), *tail = head;
for(int i = 1; i < length; i++) {
ListNode *current = new ListNode(input[i]);
tail -> next = current;
tail = tail -> next;
}
return head;
}
static void printListNode(ListNode *head) {
while(head != NULL) {
cout << head -> val << "->";
head = head -> next;
}
cout << "NULL" <<endl;
}
static void runTest(int input[], int val, int length) {
ListNode *head = arrayToList(input, length);
printListNode(head);
Solution solution;
ListNode *result = solution.removeElements(head, val);
printListNode(result);
}
public:
void sample() {
int input1[] = {1, 1}, val1 = 1, length1 = 2;
runTest(input1, val1, length1);
}
};