JAVA数据结构问题:在带头结点的单链表中,查找值为X的结点若找到则删除否则输出NO

2025-01-07 21:32:43
推荐回答(2个)
回答1:

你要是模拟的话,可以使用数组,查找每个值,存在就删除,不存在就输出No。你又不搞内部代码,模拟实现就可以了!

回答2:

package com.link;public class Node {

//前一个节点
private Node prev;//后一个节点
private Node next;

//值
private T value;public Node() {
super();
}public Node(Node prev, Node next, T value) {
super();
this.prev = prev;
this.next = next;
this.value = value;
}public Node getNext() {
return next;
}public void setNext(Node next) {
this.next = next;
}public Node getPrev() {
return prev;
}public void setPrev(Node prev) {
this.prev = prev;
}public T getValue() {
return value;
}public void setValue(T value) {
this.value = value;
}

//是否有上一个节点 或者 下一个节点
public boolean hasNext(){
if(this.next!=null)return true;
return false;
}

public boolean hasPrev(){
if(this.prev!=null)return true;
return false;
}
}
----------------------------------------package com.link;public class LinkList {

//头结点
private Node head;

//构造器
public LinkList() {
head = new Node(null,null,null);
}

public void add(T t){
Node temp = head;
while(temp.hasNext()){
temp = temp.getNext();
}
temp.setNext(new Node(temp,null,t));
}

private Node find(T t){
if(t == null)return null;
if(!head.hasNext())return null;
Node temp = head;
while(temp.hasNext()){
temp = temp.getNext();
if(t.equals(temp.getValue())){
return temp;
}
}
return null;
}

public boolean hasValue(T t){
if(find(t)!=null)return true;
return false;
}

public boolean remove(T t){
Node temp = find(t);
if(temp!=null){
temp.getNext().setPrev(temp.getPrev());
temp.getPrev().setNext(temp.getNext());
temp = null;
return true;
}
return false;
}

//按索引取节点
public T get(int index){
if(!head.hasNext())return null;
Node temp = head;
int i=0;
for(;i<=index&&temp.hasNext();i++){
temp = temp.getNext();
}
if(i == index+1)return temp.getValue();
return null;
}public static void main(String[] args) {
LinkList list = new LinkList();
for(int i=0;i<20;i++){
list.add("String"+i);
}
//以下打印只为显示结果,正常情况下不会这样打印
Node temp = list.head;
int i = 0;
while(temp.hasNext()){
temp = temp.getNext();
System.out.println("Value "+i+":"+temp.getValue());
i++;
}

if(list.remove("String10")){
System.out.println("SUCCESS");
}else{
System.out.println("NO");
}

temp = list.head;
i=0;
while(temp.hasNext()){
temp = temp.getNext();
System.out.println("Value "+i+":"+temp.getValue());i++;
}
}
}