Hri*_*sto 8 java linked-list circular-list data-structures
我想创建一个循环/循环链表,其中列表的尾部将指向列表的头部.因此,我可以java.util.LinkedList在创建列表后使用和修改尾节点以使其成为循环/循环吗?如果是这样,你能告诉我一些如何发生的代码吗?
如果我不能使用java.util.LinkedList,我应该如何创建自己的循环/循环链表实现?你能告诉我这个实现的外观吗?
如果您需要更多详细信息,请告诉我,我会清除任何困惑.
Laj*_*pad 18
class ListNode {
public ListNode next;
public Object data;
public ListNode(Object data, ListNode next) {
this.next = next;
this.data = data;
}
}
class CircularLinkedList {
private ListNode head = null;
private int numberOfElements = 0;
private ListNode actualElement = null;
private int index = 0;
public boolean isEmpty() {
return (numberOfElements == 0);
}
public int getNumberOfElements() {
return numberOfElements;
}
public void insertFirst(Object data) {
if (!(isEmpty())) {
index++;
}
ListNode listNode = new ListNode(data, head);
head = listNode;
numberOfElements++;
}
public void insertAfterActual(Object data) {
ListNode listNode = new ListNode(data, actualElement.next);
actualElement.next = listNode;
numberOfElements++;
}
public boolean deleteFirst() {
if (isEmpty())
return false;
if (index > 0)
index--;
head = head.next;
numberOfElements--;
return true;
}
public boolean deleteActualElement() {
if (index > 0) {
numberOfElements--;
index--;
ListNode listNode = head;
while (listNode.next.equals(actualElement) == false)
listNode = listNode.next;
listNode.next = actualElement.next;
actualElement = listNode;
return true;
}
else {
actualElement = head.next;
index = 0;
return deleteFirst();
}
}
public boolean goToNextElement() {
if (isEmpty())
return false;
index = (index + 1) % numberOfElements;
if (index == 0)
actualElement = head;
else
actualElement = actualElement.next;
return true;
}
public Object getActualElementData() {
return actualElement.data;
}
public void setActualElementData(Object data) {
actualElement.data = data;
}
}
Run Code Online (Sandbox Code Playgroud)
Tom*_*ský 10
对于实际应用(例如,不仅仅是玩耍或学习),我个人更喜欢Guava的Iterables.cycle方法 - 请参阅http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterables .html #cycle%28java.lang.Iterable%29.
| 归档时间: |
|
| 查看次数: |
23391 次 |
| 最近记录: |