← Linked Lists

Remove Duplicates from Sorted List

Easy
Python
def delete_duplicates(head):
    cur=head
    while cur and cur.next:
        if cur.val==cur.next.val: cur.next=cur.next.next
        else: cur=cur.next
    return head
Java
public ListNode deleteDuplicates(ListNode head){
    ListNode cur=head;
    while(cur!=null&&cur.next!=null){
        if(cur.val==cur.next.val) cur.next=cur.next.next;
        else cur=cur.next;
    } return head;
}

Key Insight

Nearly identical. Python truthiness vs Java null checks.

Python → Java Differences

  • while cur and cur.next vs !=null
  • Skip or advance identical
  • Nearly identical
Python
def delete_duplicates(head):
    cur=head
    while cur and cur.next:
        if cur.val==cur.next.val: cur.next=cur.next.next
        else: cur=cur.next
    return head
Java
public ListNode deleteDuplicates(ListNode head){
    ListNode cur=head;
    while(cur!=null&&cur.next!=null){
        if(cur.val==cur.next.val) cur.next=cur.next.next;
        else cur=cur.next;
    } return head;
}

Algorithm Steps

1. If equal skip
2. Else advance