每日一题 为了工作 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+"\t");
			current=current.next;
		}
		System.out.println();
	}
}

  

*运行结果

 

猜你喜欢

转载自www.cnblogs.com/walxt/p/12625768.html