zoukankan      html  css  js  c++  java
  • Remove Duplicates from Sorted List ,除去链表中相邻的重复元素

    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.

    public ListNode deleteDuplicates(ListNode head) {
    		if (head == null || head.next == null) {
    			return head;
    		}
    		ListNode temp = head;
    		while (temp.next != null) {
    			if (temp.next.val == temp.val) {
    				temp.next = temp.next.next;
    			}
    			else
    			{
    				temp = temp.next;
    			}
    		}
    		return head;
    	}
    

    Remove Duplicates from Sorted List II:

    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.

    算法分析:区别问题1,这个是把所有重复元素都删掉,一个不留,所有要用两重while去重,上面一题去重时只需要一重循环。

    public ListNode deleteDuplicates2(ListNode head) 
    	{
    		if(head == null || head.next == null)
    		{
    			return head;
    		}
    		ListNode pre = new ListNode(0);//记录头结点,因为开头如果有重复元素,head将改变
    		pre.next = head;
    		ListNode temp = pre;
    		while (temp.next != null && temp.next.next != null) {
    			if(temp.next.val == temp.next.next.val)
    			{
    				int dup = temp.next.val;
    				while(temp.next != null && temp.next.val == dup)//去掉所有重复元素
    				{
    					temp.next = temp.next.next;
    				}
    			}
    			else
    			{
    				temp = temp.next;
    			}
    		}
    		return pre.next;
    	}
    
  • 相关阅读:
    MariaDB + Visual Studio 2017 环境下的 ODBC 入门开发
    CUDA 9.1/9.2 与 Visual Studio 2017 (VS2017 15.6.4) 的不兼容问题
    用 SDL2 在屏幕上打印文本
    用 SDL2 处理精灵图
    用 SDL2 进行事件驱动编程
    用 SDL2 加载PNG平铺背景并显示前景
    用 SDL2 平铺背景并显示前景
    用 SDL2 显示一张图片
    VPS 安全措施(CentOS 6)
    Hello World!
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5796979.html
Copyright © 2011-2022 走看看