無需實際反轉連結串列的 JavaScript 列印反轉連結串列程式
連結串列是線性資料結構,其記憶體並非連續的。我們將用 JavaScript 編寫完整的程式碼,並提供不同的方法和示例來更好地理解這個過程。
問題介紹
在這個問題中,我們得到一個連結串列,我們必須以相反的順序列印其所有元素,但我們不必反轉給定的連結串列。
例如:
Given linked list: 1 2 3 4 5 6 Result: 6 5 4 3 2 1
我們將使用兩種方法以相反的方式列印給定的連結串列,讓我們來看看它們:
儲存在陣列中
在這種方法中,我們將按照它們在連結串列中出現的順序儲存給定連結串列的元素,然後我們將以相反的順序列印陣列的元素,因為獲取陣列的索引很容易。
示例
由於陣列是固定大小的,我們現在假設連結串列中的最大元素數為 1000,因此我們只建立此大小的陣列。讓我們看看程式碼:
<html> <body> <script> // creating class for linked list class Node { constructor(data){ this.value = data this.next = null } } // function to print elements of the linked list function print(head){ var temp = head while(temp != null) { document.write(temp.value + " ") temp = temp.next } } // function to print the elements in an opposite manner function reverse_LL(head) { var temp = head; // getting the size of the linked list count = 0; while(temp != null){ temp = temp.next count++; } var arr = new Array(count) temp = head; var i = 0 while(temp != null){ arr[i] = temp.value temp = temp.next i++ } while(i--) { document.write(arr[i] + " ") } } // creating the linked list var head = new Node(1) head.next = new Node(2) head.next.next = new Node(3) head.next.next.next = new Node(4) head.next.next.next.next = new Node(5) head.next.next.next.next.next = new Node(6) // printing the linked list document.write("The linked list is: ") print(head) document.write("<br>The linked list in reverse order is: ") reverse_LL(head) </script> </body> </html>
時間和空間複雜度
上述程式碼的時間複雜度為 O(N),其中 N 是連結串列的大小。
上述程式碼的空間複雜度為 O(N),因為我們使用額外的陣列來儲存連結串列元素。
注意:在上面的程式碼中,我們沒有將陣列大小設定為 1000,而是首先遍歷連結串列以查詢其大小,然後建立該大小的陣列。
使用遞迴
在上述方法中,我們首先找到連結串列的大小,然後使用陣列儲存元素,這使得程式碼看起來更長。為了克服這個問題,我們可以使用遞迴的概念,在這個概念中,我們將建立一個函式並將連結串列作為引數傳遞。
在遞迴函式中,我們將使用基準情況,即當前引數為空,否則我們首先呼叫下一個具有下一個節點作為引數的相同函式,然後呼叫後,我們將列印當前節點的值。
示例
這將以相反的方式列印連結串列的元素,而不會反轉給定的連結串列,讓我們看看程式碼:
<html> <body> <script> // creating class for linked list class Node{ constructor(data){ this.value = data this.next = null } } // function to print elements of the linked list function print(head){ var temp = head while(temp != null){ document.write(temp.value + " ") temp = temp.next } } // function to print the elements in the oposite manner function reverse_LL(head){ if(head == null) { return } reverse_LL(head.next) document.write(head.value + " ") } // creating the linked list var head = new Node(1) head.next = new Node(2) head.next.next = new Node(3) head.next.next.next = new Node(4) head.next.next.next.next = new Node(5) head.next.next.next.next.next = new Node(6) // printing the linked list document.write("The linked list is: ") print(head) document.write("<br>The linked list in reverse order is: ") reverse_LL(head) </script> </body> </html>
時間和空間複雜度
上述程式碼的時間複雜度為 O(N),其中 N 是連結串列的大小。
上述程式碼的空間複雜度為 O(N),這個因素是由於將包含遞迴呼叫元素的堆疊大小造成的。
結論
在本教程中,我們實現了一個 JavaScript 程式,用於列印給定連結串列的逆序,而無需反轉給定的連結串列。在第一種方法中,我們將連結串列的所有元素新增到陣列中並以相反的順序列印。在第二種方法中,我們建立了一個遞迴函式,該函式將以相反的方式列印元素。兩種方法的時間和空間複雜度均為 O(N)。