Question
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
Solution:
public class Solution {
public ListNode removeDup(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1);
ListNode prev = dummy, cur = head;
dummy.next = head;
while (cur != null && cur.next != null) {
while (cur != null && cur.next != null && cur.value == cur.next.value) {
cur = cur.next;
}
if (prev.next != cur) {
prev.next = cur.next;
cur = prev.next;
} else {
prev = cur;
cur = cur.next;
}
}
return dummy.next;
}
}
Question:
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
Solution
/**
* class ListNode {
* public int value;
* public ListNode next;
* public ListNode(int value) {
* this.value = value;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeDup(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode cur = head;
while (cur != null && cur.next != null) {
while(cur.next != null && cur.value == cur.next.value) {
cur.next = cur.next.next;
}
cur = cur.next;
}
return head;
}
}
Note: In this case, we don’t need to create a dummy node, because the head won’t be deleted anyway.