[英]Implementing Circular Linked List in java
我在实现我的循环链表时遇到了一些问题。 我正在研究一个需要您自己实施任何ADT的问题。 我似乎可以将节点添加到列表中,但是在删除时我处于一个不熟悉的领域。 我包含前两个删除方法,让您了解我的头部在哪里,如何删除列表中的最后一个节点?
public class LinkedList {
private Node head;
private Node tail;
private int size = 0;
LinkedList() {
head = null;
current = null;
previous = null;
tail = null;
size = 0;
}
//checks if list is empty
public boolean isEmpty() {
return head == null;
}
//add new node to front of circularly linked list
public void addToFront(E x) {
if (head == null) {
head = new Node(x);
} else {
Node n = new Node(x);
x.next() = head;
head = x;
}
}
public void addtoMiddle(E x) {
x.next = current.next();
current.next = x;
size = size + 1;
}
public void addToEnd(E x) {
x.next = null;
tail.next() = x;
tail = x;
size = size + 1;
}
public void removeFirst(E x) {
if (head = null) {
System.out.println("Error! List is empty!");
} else {
head = current.next();
size = size + 1;
}
}
public void removeMiddle(E x) {
previous.next() = current.next();
current.next() = null;
size = size + 1;
}
在循环链表中,最后一个节点的next
指向头部,因此您循环遍历节点,直到node.next.equals( head )
。 注意, next
必须永远不能为null,如果你只有一个节点,那么你有head.next = head
。
在循环双向链表中,您还有一个previous
节点,即您可以向后迭代。 在这种情况下,您的最后一个节点只是head.previous
。
一个小的ascii图片:
head -next---> node -next---> node -next---> last
| ^ <---prev- <---prev- <---prev- | ^
| | | |
| |_____________________________________next_| |
|_prev_________________________________________|
我知道这不是你问题的直接答案,但我觉得托马斯在这里给出了必要的解释。
由于示例中有很多语法或不完整错误,我建议将所有函数注释掉,以便它不再有错误。 然后逐一评论它们,纠正每个错误。
一些建议:
您使用未定义的类成员,例如current
, previous
。
确定next
是否应该是成员或函数。
您需要为Node
定义一个类(包含其成员和函数),就像您为LinkedList
所做的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.