zoukankan      html  css  js  c++  java
  • 每日一题 为了工作 2020 0402 第三十一题

    /**
    * 问题:删除无序单链表中值重复出现的节点
    *
    * 给定一个无序单链表的头节点head, 删除其中值重复出现的节点。
    * 例如: 1->2->3->3->4->4->2->1->1->null, 删除值重复的节点之后
    * 为 1->2->3->4->null。
    *
    * 要求:
    * 如果链表长度为 N, 时间复杂度达到 O(N)。
    *
    * 分析:
    * 利用哈希表。时间复杂度为O(N), 额外空间复杂度为O(N)。
    *
    * 具体过程如下:
    * 1.生成一个哈希表因为头节点是不用删除的节点所以首先将头节点的值放入哈希表。
    * 2.从头节点的下一个节点开始往后遍历节点, 假设遍历到 cur节点,先检测cur的
    * 值是否在哈希表中, 如果在, 则说明cur节点的值是之前出现过的, 就将 cur
    * 节点删除,删除的方式是将最近一个没有被删除的节点 pre连接到 cur的下一个
    * 节点, 即 pre.next = cur.next。如果不在,将 cur节点的值加入哈希表,
    * 同时令 pre=cur, 即更新最近一个没有被删除的节点。
    *
    * @author 雪瞳
    *
    */

    *代码

    public class Node {
    	public int value;
    	public Node next;
    	public Node(int data){
    		this.value=data;
    	}
    }
    

      

    public class RemoveBothElements {
    
    	public Node removeElements(Node head){
    		
    		if(head == null){
    			return head;
    		}
    		
    		HashSet<Integer> set = new HashSet<>();
    		Node current = null;
    		Node preCurrent = null;
    		
    		set.add(head.value);
    		preCurrent=head;
    		current=head.next;
    		while(current!=null){
    			if(set.contains(current.value)){
    				preCurrent.next=current.next;
    			}else{
    				set.add(current.value);
    				preCurrent=current;
    			}
    			current=current.next;
    		}
    		
    		return head;
    	}
    }
    

      

    import java.util.Random;
    import java.util.Scanner;
    
    public class TestRemoveBothElements {
    
    	public static void main(String[] args) {
    		TestRemoveBothElements test = new TestRemoveBothElements();
    		RemoveBothElements remove = new RemoveBothElements();
    		Scanner sc = new Scanner(System.in);
    		System.out.println("输入链表长度");
    		int len=0;
    		len =sc.nextInt();
    		Node head = test.getNodeList(len);
    		test.showNodeList(head);
    		Node result = remove.removeElements(head);
    		test.showNodeList(result);
    		sc.close();
    	}
    	public Node getNodeList(int length){
    		Random rand = new Random();
    		Node nodeArray[]= new Node[length];
    		for(int i=0;i<length;i++){
    			nodeArray[i]=new Node(rand.nextInt(10));
    		}
    		for(int i=0;i<length-1;i++){
    			nodeArray[i].next = nodeArray[i+1];
    		}
    		return nodeArray[0];
    	}
    	public void showNodeList(Node head){
    		Node current = null;
    		current = head;
    		System.out.println("链表元素如下...");
    		while(current!=null){
    			System.out.print(current.value+"	");
    			current=current.next;
    		}
    		System.out.println();
    	}
    }
    

      

    *运行结果

     

  • 相关阅读:
    js 数组扁平
    leetcode 15 三数之和
    leetcode 1 两数之和
    编写一个自定义事件类,包含on/off/emit/once方法
    css常见双栏和三栏布局
    关于js中this指向的问题
    函数防抖和节流
    ie6 js报错汇总
    windows PHP配置随笔
    上传文件表单file,限制上传文件类型的方法--参数accept
  • 原文地址:https://www.cnblogs.com/walxt/p/12618942.html
Copyright © 2011-2022 走看看