[英]size of linkedList
我是Java的新手,为我提供了Linkedlist设置,我需要使用递归或while循环来编写size函数,该函数返回链表的大小。 我想我对这个链表设置未初始化Node,head等时如何执行size函数感到非常困惑。
package list;
public class LinkedList {
public int value;
public LinkedList next;
public LinkedList (int value, LinkedList next) {
this.value = value;
this.next = next;
}
public static LinkedList list () {
return new LinkedList(1, new LinkedList(2, new LinkedList(3, null)));
}
public int size () {
int size = 0;
Node Current = head;
while(Current.next != null)
{
Current = Current.next;
size++;
}
return size;
}
}
在当前公式中, LinkedList
实例实际上LinkedList
节点又是列表。 可以,但是这意味着列表中没有明显的“头” ...
在这种情况下,解决方法是更改:
Node Current = head;
至
LinkedList current = this;
(并且,是的, size
变量应以1
开头。在此公式中,空列表由null
表示。如果要在LinkedList
的实例上调用size()
,则列表的大小必须至少为1。 )
@Konrad指出“列表本身应该封装节点”。
实际上,这是一种设计选择。 如果您遵循OO设计原则,那么应该这样做。 但是,在某些情况下,您实际上不想这样做。 有时有必要“牺牲”抽象以获得更好的性能或降低内存利用率。
在链接列表(如您创建的列表)中计算大小的另一种方法是使用递归。 只有两种情况:
1
仅其自身 1
加下一个的大小。 因此,我们具有以下功能:
public int size(){
if(next == null){
return 1;
} else {
return 1 + next.size();
}
}
这可以使用三元运算符非常简洁地编写:
public int size(){
return next != null ? 1 + next.size() : 1;
}
对于迭代解决方案,无需使用Node
类,因为每个LinkedList
对象都表示自身(一个值)和所有要遵循的值(值列表)。 从这个角度来看,我们必须从“这里”循环直到无处可去。
public int size () {
int size = 1;
LinkedList Current = this;
while(Current.next != null){
Current = Current.next;
size++;
}
return size;
}
public int size()
{
int size = 1;
LinkedList head = this;
while (head.next != null)
{
head = head.next;
size++;
}
return size;
}
像这样更改它:
public int size () {
int size = 0;
// set the head as current note
Node current = head;
// while a current node is set
while(current != null)
{
// increment site
size++;
// and set the next as current node
current = current.next;
}
return size;
}
列表本身不是列表。 这是节点的链接列表。 列表本身应该封装节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.