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();
    	}
    }
    

      

    *运行结果

     

  • 相关阅读:
    jquery ajax和php实现返回值 json类型
    jQuery一句话实现多选框全选/取消
    九宫格拼图 支持44 55等
    php通过$_SERVER['HTTP_USER_AGENT']获取浏览器useAgent
    微信刮刮卡代码
    从QQ网站中提取的纯JS省市区三级联动
    Codeigniter+PHPExcel导出数据到Excel文件
    flv视频播放器停止时带图片
    html5+js实现刮刮卡效果
    解决Tensorflow 使用时cpu编译不支持警告:that this TensorFlow binary was not compiled to use: AVX AVX2
  • 原文地址:https://www.cnblogs.com/walxt/p/12625768.html
Copyright © 2011-2022 走看看