本文介绍了查找双链表的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在计算双向链接列表中的元素时遇到了一些麻烦
I am having some trouble with counting the elements of my doubly linked list
这是节点类:
public class Node {
private Node previous, next;
private Object data;
public Node(Object data) {
this.data = data;
}
public Node() {
}
public Node(Object data, Node previous, Node next) {
this.previous = previous;
this.next = next;
this.data = data;
}
public Node getPrevious() {
return previous;
}
public void setPrevious(Node previous) {
this.previous = previous;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
这是我的双向链表方法
public class DList {
private Node base;
public DList() {
}
/**
* Return the number of elements in the list.
*/
public int size() {
int count = 0;
if (base == null)
return count;
else {
Node temp = base;
do {
temp = temp.getNext();
count++;
} while (temp != base);
}
return count;
}
}
测试时,结果应该是5,但是我的函数没有计算任何东西.谢谢您的帮助!
when testing, the result should be 5, but my function isn't counting anything. Thanks for the help!
推荐答案
在base是唯一元素的情况下,其他答案不太有效.应该要一段时间,例如:
The other answer won't quite work, in the case where base is the only element. It should be a while, like:
public int size() {
int count = 0;
if (base.getNext() == base)
return count;
else {
Node temp = base.getNext();
while (temp != base) {
temp = temp.getNext();
count++;
}
}
return count;
}
您的代码假设您使用的是圆形双向链接列表,并且假定为以空值结尾的列表.你要去哪?
Your code was assuming that you were using a circular doubly-linked list, and this assumes a null-terminated list. Which were you going for?
这篇关于查找双链表的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!