我使用自己的链表,有人可以告诉我如何在特定位置添加新链接到列表吗?说我想做.add(3,4)所以它会在列表的第4个链接中添加元素4(因为0是第一个)? (我不想使用API中的LinkedList,我知道有一种方法可以在那里执行此操作)
//Doubly linked list of integers
public class DLinkedList {
DLink _firstLink;
DLink _lastLink;
public DLinkedList()
{
}
public boolean isEmpty()
{
return (_firstLink==null);
}
public void addFirst(int e)
{
DLink newLink = new DLink(e);
if(isEmpty())
{
_lastLink = newLink;
}
else
{
_firstLink._previous = newLink;
}
newLink._next = _firstLink;
_firstLink = newLink;
}
public void add(int index, int e)
{
//how do I add a DLink in the i'th spot of the linked list?
}
public void addLast(int e)
{
DLink newLink = new DLink(e);
if(isEmpty())
{
_firstLink = newLink;
}
else
{
_lastLink._next = newLink;
newLink._previous = _lastLink;
}
_lastLink= newLink;
}
}
答案 0 :(得分:0)
public void add(int index, int e)
{
DLink iterator=_firstLink;
int count=0;
while(iterator!=_lastLink)
{
if(count>=index)break;
iterator=iterator._next;
count++;
}
if(index==count)
{
DLink newLink = new DLink(e);
newLink._previous=iterator._previous;
newLink._next=iterator;
iterator._previous=newLink;
}
else throw new Exception("IndexOutOfBoundException");
}