Question
Formatted question description: https://leetcode.ca/all/83.html
83 Remove Duplicates from Sorted List
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
@tag-linkedlist
Algorithm
Traverse this linked list, and compare each node with the following nodes. If the value of the node is the same, just skip the next pointer of the previous node with the same value and point to the next node. After traversing in this way, all duplicate nodes will be skipped, and the linked list left will have no duplicates.
Code
Java
-
public class Remove_Duplicates_from_Sorted_List { /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) return head; // ListNode dummy = new ListNode(0); // dummy.next = head; ListNode prev = head; ListNode p = head.next; while (p != null) { if (p.val == prev.val) { prev.next = p.next; p = p.next; } else { prev = p; p = p.next; } } return head; } } }
-
Todo
-
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ dummy = ListNode(None) dummy.next = head p = dummy while p and p.next: if p.val == p.next.val: p.next = p.next.next else: p = p.next return dummy.next