LeetCode – 83. Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appears only once.

For example,
Given 1->1->2return 1->2.
Given 1->1->2->3->3return 1->2->3.

This was my first linked list problem. Although it was very simple, I found many pitfalls. I suggest writing a few by hand.

Another thing to consider is, what if it's not sorted?

Second question: What if it's not sorted and you're not allowed to use extra space?

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

This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:

Original author:Jake Tao,source:"LeetCode – 83. Remove Duplicates from Sorted List"

132
0 0 132

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top