[英]remove from double linked list
I am to java and I am trying to implement a remove from double linked list method but I am struggling and not sure how to advance.我是Java,我正在尝试实现从双链表中删除的方法,但我很挣扎,不知道如何推进。 The method removes data stored at the given node in the list.
该方法删除存储在列表中给定节点的数据。 I have read that I need to account for cases where the the element being removed is the start or end but I am not sure how to go about.
我已经读到我需要考虑被删除的元素是开始或结束的情况,但我不知道如何去做。 In general I am not sure if this is the right way to do it.
一般来说,我不确定这是否是正确的方法。 My code/progress is posted below.
我的代码/进度发布在下面。 If any could help, it would be appreciated.
如果有任何帮助,将不胜感激。 Thanks
谢谢
PS I have a start and an end reference within the class and a size reference PS我在类中有一个开始和结束参考以及一个大小参考
public type removeAtTheIndex(int index)
{
type theData = null;
Node <type> current= start;
Node temp= new Node();
if (index >= 0 && index < size && start !=null)
{
for (int i=0; i < index && current.getNext()!= null; i++)
{
current=current.getNext();
}
if (current != null)
{
if (current == start)
{
}
else if (current == end)
{
}
else
{
theData= current.getData();
temp= current.getPrev();
temp.setNext(current.getNext());
current.getNext().setPrev(temp);
current.setData(null);
size--;
}
}
return theData;
}
I have changed the type
to Type
.我已将
type
更改为Type
。 Using lowercase for class names is not recommended in Java.在 Java 中不推荐使用小写的类名。 I have added loads of comments in the hope that you will understand what is going on.
我添加了大量评论,希望您能理解发生了什么。
Note that this is not tested code.请注意,这不是经过测试的代码。 You may find bugs in it but I am confident that the essence of process is there.
您可能会在其中发现错误,但我相信流程的本质就在那里。
public Type removeAtTheIndex(int index) {
// I want to return the data that was removed.
Type theData = null;
// Sanity checks.
if (index >= 0 && index < size && start != null) {
// Find the entry with the specified index.
Node<Type> current = start;
for (int i = 0; i < index && (current = current.getNext()) != null; i++) {
}
// Did we find it?
if (current != null) {
// Yes! Gather the contents.
theData = current.getData();
// Clear it.
current.setData(null);
// Special?
if (current == start) {
// Its the start one.
start = start.getNext();
// Detach it.
start.setPrev(null);
} else if (current == end) {
// Step end back one.
end = end.getPrev();
// Detach it.
end.setNext(null);
} else {
// Remove from within list.
Node prev = current.getPrev();
// Point it at my next.
prev.setNext(current.getNext());
// Point my next to new prev.
current.getNext().setPrev(prev);
}
// One less now.
size--;
}
}
return theData;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.