用JAVA编写链表类,要求编写能够从头部添加节点。

2025-03-23 17:15:52
推荐回答(3个)
回答1:

public class ZLinkedList {
private int size;
private Node head;
public ZLinkedList(){
size = 0;
}
public void headInsert(Object obj){
//if(null== obj) {// do something}
Node temp = new Node(obj);
if(size ==0){
head = temp;
}else{
temp.setNext(head);
head = temp;
}
size++;

}

public void preOrder(){
int length = size;
Node temp = head;
for(int i= 0;i < length;i ++){
System.out.println(temp.getValue());
temp = temp.getNext();
}
}

private static class Node{
private Object value;
private Node next;
Node(){
}
Node(Object val){
this.value = val;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}

}

public static void main(String[] args) {
ZLinkedList test = new ZLinkedList();
test.headInsert("1");
test.headInsert("2");
test.headInsert("3");
test.preOrder();

}
}

回答2:

这写一下费时间,建议你看《Java数据结构和算法》一书,第五章就有你想要的,的这种是单向链表,还有双向链表,这本书里面有现成的示例代码的。

回答3:

java里面有LinkedList,可以直接用,链表的功能都有,addFirst(),将指定元素插入此列表的开头。