zoukankan      html  css  js  c++  java
  • 83. Remove Duplicates from Sorted List

    题目:

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

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

    链接: http://leetcode.com/problems/remove-duplicates-from-sorted-list/

    一刷,在考虑什么时候应该使用dummy node,什么时候不应该。感觉跟第一个元素有关,如果第一个元素肯定在输出中,可以不使用dummy node。

    class Solution(object):
        def deleteDuplicates(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            if not head:
                return head
            prev = head
            current = head.next
            
            while current:
                if prev.val == current.val:
                    prev.next = current.next
                else:
                    prev = prev.next
                current = current.next
            return head

    2/14/2017, Java

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode deleteDuplicates(ListNode head) {
    11         if (head == null) return null;
    12         ListNode current = head;
    13 
    14         while (current != null) {
    15             if (current.next != null && current.next.val == current.val) current.next = current.next.next;
    16             else current = current.next;
    17         }
    18         return head;
    19     }
    20 }
  • 相关阅读:
    ORACLE CLIENT客户端安装步骤详解
    mkswap 把一个分区格式化成为swap交换区
    编译安装lnmp
    使用源代码安装lnmp
    查看nginx编译安装
    linux lnmp编译安装
    nginx编译安装
    lnmp脚本
    搭建LAMP测试环境
    绝路上的桥
  • 原文地址:https://www.cnblogs.com/panini/p/5586337.html
Copyright © 2011-2022 走看看