【发布时间】:2014-02-21 16:38:29
【问题描述】:
我正在尝试为我的链表类创建一个添加和删除方法。我用名称 Head 和 Tail 做了 2 次引用。
头部 -> 1 -> 2 -> 3 -> 尾部:空
当我尝试删除特定节点时,我不断遇到问题,因为 Java 说我越界了。我认为这是因为我的 Head 没有指向第一个节点?你们有什么感想?或者我是不是走错了路……
public class LinkedList{
private Node head;
private Node tail;
private int listCount;
public LinkedList()
{
head = new ListNode(null);
tail = new ListNode(null);
listCount = 0;
}
public void add(Object elem){
ListNode newNode = new ListNode(elem);
if (size() == 0){
newNode = head;
tail = head;
}
newNode.setLink(tail);
tail = newNode;
listCount++;
}
public Object delete(int index)
// post: removes the element at the specified position in this list.
{
// if the index is out of range, exit
if(index < 1 || index > size())
throw new IndexOutOfBoundsException();
ListNode current = head;
for(int i = 1; i < index; i++)
{
if(current.getLink() == null)
throw new IndexOutOfBoundsException();
current = current.getLink();
}
current.setLink(current.getLink().getLink());
listCount--; // decrement the number of elements variable
return current.getInfo();
}
public int size() {
return listCount;
}
}
public class Node {
private Node link;
private Object info;
public Node(Object info)
{
this.info = info;
link = null;
}
public void setInfo(Object info)
{
this.info = info;
}
public Object getInfo()
{
return info;
}
public void setLink(Node link)
{
this.link = link;
}
public Node getLink()
{
return link;
}
}
【问题讨论】:
-
这里是一个疯狂的猜测,但
newNode.setLink(tail)应该是相反的方式? -
@webuster 我不确定你的意思,你能详细说明一下吗?谢谢欣赏!
标签: java linked-list nodes