zoukankan      html  css  js  c++  java
  • [LeetCode]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.

    思路:

    给定一个已经排序的list链表,删除所有重复的元素。设定first代表首元素,second代表它的下一位。如果second不等于空,表示后面还有,继续循环;当first的
    值等于second的值时,first的下一位等于second的下一位,即将first之前代表的那位从链表中删除,second=second.next。如果不相等,则first= second
    second= second.next。最后返回head,即为删除了重复元素的链表。时间上只需要遍历一次,为O(n),空间上维护两个额外Node,为O(1)。
    不知道怎么写测试用例。链表怎么输出啊==、

     1 public class Solution83 {
     2     public ListNode deleteDuplicates(ListNode head) {
     3             if(head == null) return null;
     4             ListNode first = head;
     5             ListNode second = first.next;
     6             while(second != null){
     7                 if(second.val == first.val){
     8                     first.next = second.next;
     9                 }
    10                 else {
    11                     first = second;                
    12                 }
    13                 second = second.next;
    14                 
    15             }
    16             return head;
    17     }
    18     public static void main(String[] args) {
    19         // TODO Auto-generated method stub
    20         //不会写测试用例,ListNode怎么赋值啊
    21         Solution83 solution83 = new Solution83();
    22         ListNode head = new ListNode(1);
    23         head.next = new ListNode(1);
    24         head.next = new ListNode(2);
    25         head.next = new ListNode(3);
    26         
    27         solution83.deleteDuplicates(head);
    28         if(head.next!=null){
    29             System.out.println(head.next.val);
    30         }
    31             
    32     }
    33 
    34 }
  • 相关阅读:
    HTML的<head>中的内容总结
    毕业设计
    win7中protel99添加元件库
    E题
    D 题
    C 题 KMP中next[]问题
    B题 Sort the Array
    A题
    CSU1350 To Add which?
    CodeForce 448C 木片填涂问题
  • 原文地址:https://www.cnblogs.com/zlz099/p/8144993.html
Copyright © 2011-2022 走看看