我认为正确插入值也可以在控制台屏幕上查看,但搜索方法不能以奇怪的方式工作
我所有的代码都缺了什么?它非常清晰和基本的结构
在输出部分";43〃;通常包括在结构上,它需要显示真实,但可能不起作用,我不知道原因。输出:43 43 33 43 13 3检查:错误
NodeList head;
public void insert(int insertKey) {
NodeList myhead = new NodeList();
if (head == null) {
myhead.setData(insertKey);
} else {
myhead.setData(insertKey);
myhead.setLink(head);
}
head = myhead;
}
public boolean search(int key) {
boolean check = false;
NodeList current = head;
while (current != null) {
if (current.getData() == key) {
check = true;
break;
}
current = current.getLink();
}
return check;
}
public void display() {
if (head == null) {
} else {
while (head != null) {
System.out.print(head.getData() + " ");
head = head.getLink();
}
System.out.println();
}
}
package ds_project;
public class NodeList {
private NodeList Link;
private int data;
public NodeList(int data) {
this.Link = null;
this.data = data;
}
public NodeList() {
}
public NodeList getLink() {
return Link;
}
public void setLink(NodeList Link) {
this.Link = Link;
}
public int getData() {
return this.data;
}
public void setData(int data) {
this.data = data;
}
result screen
SLL Linkedlist = new SLL();
Linkedlist.insert(3);
Linkedlist.insert(13);
Linkedlist.insert(43);
Linkedlist.insert(33);
Linkedlist.insert(43);
Linkedlist.insert(43);
Linkedlist.display();
boolean check=Linkedlist.search(43);
System.out.println("check: " + check);}
输出:43 43 33 43 13 3检查:错误
显示方法错误,head
将成为tail
节点。使用临时节点:
public void display() {
NodeList tmp = head;
if (tmp != null) {
while (tmp != null) {
System.out.print(tmp.getData() + " ");
tmp = tmp.getLink();
}
System.out.println();
}
}
编辑:我的测试代码:
public class NodeList {
private NodeList Link;
private int data;
public NodeList(int data) {
this.Link = null;
this.data = data;
}
public NodeList() {
}
public NodeList getLink() {
return Link;
}
public void setLink(NodeList Link) {
this.Link = Link;
}
public int getData() {
return this.data;
}
public void setData(int data) {
this.data = data;
}
NodeList head;
public void insert(int insertKey) {
NodeList myhead = new NodeList();
if (head == null) {
myhead.setData(insertKey);
} else {
myhead.setData(insertKey);
myhead.setLink(head);
}
head = myhead;
}
public boolean search(int key) {
boolean check = false;
NodeList current = head;
while (current != null) {
if (current.getData() == key) {
check = true;
break;
}
current = current.getLink();
}
return check;
}
public void display() {
NodeList tmp = head;
if (tmp != null) {
while (tmp != null) {
System.out.print(tmp.getData() + " ");
tmp = tmp.getLink();
}
System.out.println();
}
}
public static void main(String[] args) {
NodeList Linkedlist = new NodeList();
Linkedlist.insert(3);
Linkedlist.insert(13);
Linkedlist.insert(43);
Linkedlist.insert(33);
Linkedlist.insert(43);
Linkedlist.insert(43);
Linkedlist.display();
boolean check=Linkedlist.search(43);
System.out.println("check: " + check);
}
}