zoukankan      html  css  js  c++  java
  • [LeetCode] 82. Remove Duplicates from Sorted List II [Java]

    题目:

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 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) {
            ListNode res = new ListNode(0);
            ListNode p = res;
            ListNode node = head;
            ListNode preNode = null;        //记录当前点的前一个点
            ListNode nextNode = null;       //记录当前点的后一个点
    
            while(node !=null){
                nextNode = node.next;
                if(preNode==null){      //第一个点
                    if(nextNode ==null || (nextNode.val != node.val)){      //只有一个点的情况或者只有第一个点和后一个点不相同,加入对列
                        p.next = node;
                        p = p.next;
                    }
                }else{
                    //(1)如果是最后一个点,那么如果该点和前面点不一样加入链表,(2)或者中间点,和前后的值都不一样加入链表
                    if((nextNode == null && (preNode.val!=node.val)) || (nextNode !=null && nextNode.val != node.val && (preNode.val!=node.val))){
                        p.next = node;
                        p = p.next;
                    }
                }
                preNode = node;
                node = nextNode;
            }
            p.next = null;
            return res.next;
        }
    }
  • 相关阅读:
    Splunk数据处理
    使用http://start.spring.io/ 生成工程
    SpringBoot和SpringCloud区别
    Spring Cloud
    Spring Boot
    Splunk大数据分析经验分享
    Splunk和ELK深度对比
    Git 教程
    Docker 教程
    STL中的unique和unique_copy函数
  • 原文地址:https://www.cnblogs.com/271934Liao/p/8053483.html
Copyright © 2011-2022 走看看