-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveDuplicatesFromLinkedList.java
More file actions
42 lines (40 loc) · 1.07 KB
/
Copy pathRemoveDuplicatesFromLinkedList.java
File metadata and controls
42 lines (40 loc) · 1.07 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
/**
* Problem:
* Given the head of a sorted linked list, delete all duplicates such that each element appears only once.
* Return the linked list sorted as well.
*
* Input: head = [1,1,2]
* Output: [1,2]
*
* Input: head = [1,1,2,3,3]
* Output: [1,2,3]
**/
// * Definition for singly-linked list.
class ListNode
{
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution
{
public ListNode deleteDuplicates(ListNode head)
{
ListNode curr = head;
//while there is a next value in List
while(curr != null)
{
//compare current val with value in next node
while((curr.next != null) && (curr.val == curr.next.val))
{
//move curr's pointer to next next node
curr.next = curr.next.next;
}
//move curr to next node
curr = curr.next;
}
return head;
}
}