-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path203.RemoveElements.cs
64 lines (61 loc) · 1.53 KB
/
203.RemoveElements.cs
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
//203. Remove Linked List Elements
// Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and
// return the new head.
// definition for singly-linked list.
public class listnode
{
public int val;
public listnode next;
public listnode(int val = 0, listnode next = null)
{
this.val = val;
this.next = next;
}
}
public class Solution
{
public listnode RemoveElements(listnode head, int val)
{
listnode pivot = head;
if (head == null)
{
return head;
}
while (head.val == val)
{
if (head.next == null)
return null;
head = head.next;
}
while (pivot != null)
{
while (pivot.next != null && pivot.next.val == val)
{
pivot.next = pivot.next.next;
}
pivot = pivot.next;
}
return head;
}
}
public class Solution {
public ListNode RemoveElements(ListNode head, int val) {
if(head == null)
return head;
while(head.val == val){
if(head.next == null)
return null;
head = head.next;
}
ListNode curr = head.next;
ListNode prev = head;
while(prev != null && curr !=null){
if(curr.val == val)
prev.next = curr.next;
else
prev = curr;
curr = curr.next;
}
return head;
}
}