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;
    	}
    
  • 相关阅读:
    C++开发系列-友元函数 友元类
    C++开发系列-C语言的malloc与C++的new分配空间
    C++开发系列-内联函数
    iOS开发系列-Foundation与CoreFoundation内存管理
    C开发系列-字符串
    C开发系列-数组
    列表 元组 字典
    神奇的print
    while 语句的逻辑
    <Web Crawler><Java><thread-safe queue>
  • 原文地址:https://www.cnblogs.com/masterlibin/p/5796979.html
Copyright © 2011-2022 走看看