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

    /**
     * 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) {
            //两种解法:
            //一种声明三个节点,一个代表index之前的均满足要求,first是遍历的节点,pre是first的前置,便于删除节点时保留前置
            //一种是只需要一个节点,该节点和其后置值进行比较,如果相等,直接删除,如果不等指向下一节点
            if(head==null||head.next==null) return head;
          /*  ListNode pre=head;
            ListNode first=head.next;
            ListNode index=head;
            while(first!=null){
                if(index.val==first.val){
                    pre.next=first.next;
                    first=first.next;
                }else{
                    pre=first;
                    first=first.next;
                    index=index.next;
                }
            }
            return head;*/
            ListNode pre=head;
            while(pre.next!=null){
                if(pre.next.val==pre.val){
                    pre.next=pre.next.next;
                }else{
                    pre=pre.next;
                }
            }
            return head;
        }
    }
  • 相关阅读:
    4. Qt的容器类
    hdu 4507 数位dp(求和,求平方和)
    MVC3和MVC4中CRUD操作
    SSL 中证书能否够使用IP而不是域名
    TinyXml快速入门(一)
    C++ TinyXml操作(含源码下载)
    Tinyxml 操作XML
    msxml 操作xml
    MFC中全局变量的定义及使用
    VC++中操作XMLWin32实例
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4647943.html
Copyright © 2011-2022 走看看