83 Remove Duplicates From Sorted List


title: Remove Duplicates From Sorted List
tags:
- remove-duplicates-from-sorted-list
- No.83
- simple
- list


Description

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

Corner Cases

  • empty list

Solutions

Naive

Here we propose a new method to process list, that is adding a new Head before the original list.

0.
[old head] -> [x] -> [x] -> [x]
1.
[new head] -> [old head] -> [x]

This will make it more convenient for a pointer to traverse and compare.

Since the list is sorted, we only record the maxmium. The running time is O(n).

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        int      m = -2147483648;        
        ListNode a = new ListNode(0);
        a.next     = head;
        ListNode p = a;        
        while (p.next != null) {
            if (m >= p.next.val) {
                p.next = p.next.next;
            }
            else {
                m = p.next.val;
                p = p.next;
            }
        }        
        return a.next;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,424评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,797评论 0 23
  • 想知道上班之后我在家里的状态么, 除了跟果果同学折腾, 然后就是等你回来。 基因是个很神奇的东西对不对, 都说果果...
    咪唏阅读 223评论 0 0
  • 独立是每个人必备的技能。因为只有独立 ,不管你走到哪,都会是自己的太阳! 以前总以为,不管遇到什么事情,父母都会是...
    尉璐璐阅读 148评论 2 0
  • Install OpenWRT on an X86 platform. Following the instruc...
    3c937c88e6c0阅读 856评论 0 1