Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
public class Solution { public ListNode deleteDuplicates(ListNode head) { // Start typing your Java solution below // DO NOT write main() function ListNode cur = head; if(head == null||head.next == null)return head; while(cur.next!= null){ if(cur.val == cur.next.val){ cur.next = cur.next.next; }else{ cur = cur.next; } } return head; } }
import java.util.*; public class Solution { public ListNode deleteDuplicates(ListNode head) { // Start typing your Java solution below // DO NOT write main() function Hashtable table = new Hashtable(); ListNode node = head; ListNode previous = null; while(node !=null ){ if(table.containsKey(node.val)){ previous.next = node.next; } else{ table.put(node.val, true); previous = node; } node = node.next; } return head; } }