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

    /***
    * 题目:删除单链表中指定值的节点
    * 给定一个链表的头节点 head和一个整数 num, 请实现函数将值为 num的节点全部删除。
    * 例如, 链表为1->2->3->4->null, num=3, 链表调整后为: 1->2->4->null。
    *
    * 解题:利用栈将不等于 num的节点全部删除再重新连接即可
    *
    * @author 雪瞳
    *
    */

    *代码

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

      

    public class DeleteNodeByValue {
    
    	private Stack<Node> stack = null;
    	private Node current = null;
    	public Node deleteNodeByValue(Node head,int num){
    		
    		stack = new Stack<>();
    		current = head;
    		
    		while(current!=null){
    			if(current.value!=num){
    				stack.push(current);
    			}
    			current=current.next;
    		}
    		//current = null;
    		while(!stack.isEmpty()){
    			stack.peek().next = current;
    			current = stack.pop();
    		}
    		
    		return current;
    	}
    }
    

      

    import java.util.Random;
    import java.util.Scanner;
    
    
    public class TestDeleteNodeByValue {
    
    	public static void main(String[] args) {
    		
    		TestDeleteNodeByValue test = new TestDeleteNodeByValue();
    		DeleteNodeByValue delete = new DeleteNodeByValue();
    		Scanner sc = new Scanner(System.in);
    		System.out.println("请输入链表长度...");
    		int len=0;
    		len =sc.nextInt();
    		Node head = test.getNodeList(len);
    		System.out.println("请输入删除的元素值...");
    		int num=0;
    		num =sc.nextInt();
    		
    		//test
    		test.showNodeList(head);
    		Node result = delete.deleteNodeByValue(head, num);
    		test.showNodeList(result);
    	}
    	
    	//获取链表
    	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();
    	}
    }
    

      

    *运行结果

     

  • 相关阅读:
    ffmpeg一些filter使用方法、以及一些功能命令
    Hibernate调试——定位查询源头
    emmet语法
    [心得]传统IT转互联网面试经验分享
    Java中的集合类型的继承关系图
    Java的IO操作中有面向字节(Byte)和面向字符(Character)两种方式
    oracle求时间差的常用函数
    jdbc读取新插入Oracle数据库Sequence值的5种方法
    Xpath语法格式整理
    Oracle中 Instr 这个函数
  • 原文地址:https://www.cnblogs.com/walxt/p/12625768.html
Copyright © 2011-2022 走看看