首页 > 其他 > 详细

每日一题 为了工作 2020 0403 第三十二题

时间:2020-04-03 14:36:58      阅读:56      评论:0      收藏:0      [点我收藏+]

/***
* 题目:删除单链表中指定值的节点
* 给定一个链表的头节点 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+"\t");
			current=current.next;
		}
		System.out.println();
	}
}

  

*运行结果

技术分享图片

 

 

每日一题 为了工作 2020 0403 第三十二题

原文:https://www.cnblogs.com/walxt/p/12625768.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!