-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveDuplicatesfromLinkedList.java
More file actions
49 lines (44 loc) · 1.04 KB
/
RemoveDuplicatesfromLinkedList.java
File metadata and controls
49 lines (44 loc) · 1.04 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
/*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 */
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null)
return null;
ListNode prev=head;
ListNode cur=null;
if(head.next!=null)
cur=head.next;
else
{
if(head.val==val)
return null;
}
while(cur!=null)
{
if(cur.val==val)
{
prev.next=cur.next;
cur=prev.next;
}
else
{
prev=cur;
cur=prev.next;
}
}
if(head.val==val)
return head.next;
else
return head;
}
}