[英]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.