问题描述
我正在实现一个通用的链表,但是我很难编写一个返回当前节点的函数。它总是返回最后添加的节点。我在下面分享我的代码。
我搜索过类似的问题,但没有找到我想要的。
这是链表文件。我确定 vorne() 的 add 方法按预期工作。它在开头添加元素。
public class Liste<T> {
// Points to the head of the Linked List
// i.e the first element
Node<T> head;
Node<T> tail;
static int size = 0;
static class Node<T> {
// Data Stored in each Node of the Linked List
T data;
// Pointer to the next node in the Linked List
Node<T> next;
// Node class constructor used to initializes the data
// in each Node
private Node(T data) {
this.data = data;
next = null;
}
}
public static <T> Liste<T> neu() {
Liste<T> l = new Liste<T>();
return l;
}
public static <T> Liste<T> einfuegen(Liste o,T auD,Nat nat) {
return null;
}
// Add element at the beginning
public static <T> Liste<T> vorne(Liste<T> list,T data) {
//Create new node
Node newNode = new Node(data);
//Checks if the list is empty.
if(list.head == null) {
//If list is empty,both head and tail would point to new node.
list.head = newNode;
list.tail = newNode;
newNode.next = list.head;
size++;
}
else {
//Store data into temporary node
Node temp = list.head;
//New node will point to temp as next node
newNode.next = temp;
//New node will be the head node
list.head = newNode;
//Since,it is circular linked list tail will point to head.
list.tail.next = list.head;
size++;
}
return list;
}
// This method should return the last added element
public static <T> T kopf(Liste<T> lNat) {
// Throws an Exception if the List is empty
if (lNat.head == null) {
System.out.print("No Element found");
}
return lNat.head.data;
}
// This method should return all the elements except the first element.
public static <T> Liste<T> rest(Liste<T> lString) {
// Todo Auto-generated method stub
if (lString.head != null) {
lString.head = lString.head.next;
}
return lString;
}
public int getCount() {
return size;
}
}
问题出在这里!
public static void main(String[] args) {
// Todo Auto-generated method stub
Liste<String> l0 = Liste.neu();
Liste<String> l1a = Liste.vorne(l0,"AuD");
Liste<String> l1b = Liste.vorne(l0,"PFP");
Liste<String> l2a = Liste.vorne(l1a,"FAUL");
Liste<String> l2b = Liste.vorne(l1b,"FAIL");
//Liste<String> l1x = Liste.rest(l2b);
//Liste<String> l1y = Liste.rest(l2b);
//Liste<String> l0x = Liste.rest(l1x);
//Liste<String> l0y = Liste.rest(l1y);
//String l0y = Liste.kopf(l2a);
System.out.println(l1b.getCount());
System.out.println(Liste.kopf(l2a));
}
输出:
4
FAIL
当我调用应该返回最后添加的元素的 kopf 方法时,它返回字符串“FAIL”而不是“FAUL”。我将它存储在一个单独的对象中,并且我正在调用 l2a 对象,那么为什么它返回“FAIL”。如您所见,我正在使用 neu() 方法创建一个新列表,然后使用相同的列表添加元素。我认为这是一个我没有看到的愚蠢错误。 好像想不通了请提供任何帮助,我们将不胜感激。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)