无需实际反转链表的 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)。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP