下面是我自己写的,编译肯定是过不了的。我不明白的是,是否要接入接口LList,数组要怎么
实现,怎样打印在屏幕上,怎样写,需要怎么改,这类的编程在MyEclipse上要怎么写,是否
要分开写。谢谢你们了,拜托了
class Node{
public T data;
public Node next;
public Node(T data,Node next){
this.data=data;
this.next=next;
}
public Node(){
this(null,null);
}
}
class SinglyLinkedList{
protected Node head;
public SinglyLinkedList(){
this.head=new Node();
}
public SinglyLinkedList(T[] element){
this();
for(int i=0;i head.next=new Node(element[i],head.next);
}
}
}
public class Ex2_1{
public static void main(String args[]){
SinglyLinkedList s=new SinglyLinkedList();
T[] element={ 6,2,11,5,2,4,2};
System.out.print();
}
}
该回答引用ChatGPT
首先,你需要为你的 SinglyLinkedList 类添加一个泛型参数来表示你要创建的单链表中节点的数据类型。例如,你可以这样声明你的 SinglyLinkedList 类:
class SinglyLinkedList<T> {
//...
}
然后,你需要添加一个 LList 接口,该接口应该定义单链表的基本操作,例如,插入,删除和遍历等。你可以这样声明你的 LList 接口:
interface LList<T> {
public void insert(T data); //在单链表的头部插入一个节点
//其他操作,例如删除和遍历等
}
接下来,你需要使用前插法来构建你的单链表。在前插法中,你应该将新节点插入到单链表的头部。以下是一个实现前插法的示例代码:
class SinglyLinkedList<T> implements LList<T> {
//...
public void insert(T data) {
Node<T> newNode = new Node<>(data, head.next);
head.next = newNode;
}
//...
}
注意,在上面的代码中,我们首先创建一个新节点 newNode,该节点的数据为 data,它的 next 指向 head.next,然后我们将 head.next 指向 newNode,这样就完成了一个节点的插入。
最后,在 main 方法中,你可以创建一个 SinglyLinkedList 对象,并使用 insert 方法插入节点,例如:
public static void main(String args[]){
SinglyLinkedList<Integer> s = new SinglyLinkedList<>();
Integer[] element = {6, 2, 11, 5, 2, 4, 2};
for(Integer i : element) {
s.insert(i);
}
//遍历单链表并打印节点数据
Node<Integer> cur = s.head.next;
while(cur != null) {
System.out.print(cur.data + " ");
cur = cur.next;
}
}
这将打印出以下内容:
2 4 2 5 11 2 6