Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
59 lines (48 loc) · 1.31 KB

File metadata and controls

59 lines (48 loc) · 1.31 KB
Copy raw file
Download raw file
Outline
Edit and raw actions

Difficulty: Easy

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

Language: Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode curr = head;
        ListNode nextIndex = head;
        while (curr.next != null) {
            while (curr.next != null && curr.val == curr.next.val) {
                curr = curr.next;
            }
            if (curr != nextIndex) {
                nextIndex.next = curr.next;
                nextIndex = curr;
            } else {
                curr = curr.next;
                nextIndex = nextIndex.next;
            }
        }
        return head;
    }
}

pic

Morty Proxy This is a proxified and sanitized view of the page, visit original site.