📌  相关文章
📜  用于编写函数以获取链表中第 N 个节点的 Javascript 程序

📅  最后修改于: 2022-05-13 01:57:45.575000             🧑  作者: Mango

用于编写函数以获取链表中第 N 个节点的 Javascript 程序

编写一个 GetNth()函数,该函数接受一个链表和一个整数索引,并返回存储在该索引位置的节点中的数据值。

例子:

Input:  1->10->30->14,  index = 2
Output: 30  
The node at index 2 is 30

算法:

1. Initialize count = 0
2. Loop through the link list
     a. If count is equal to the passed index then return 
        current node
     b. Increment count
     c. change current to point to next of the current.

执行:

Javascript


Javascript


输出:

Element at index 3 is 4

时间复杂度: O(n)

方法 2- 使用递归:
此方法由 MY_DOOM 提供。

算法:

getnth(node,n)
1. Initialize count = 0
2. if count==n
     return node->data
3. else
    return getnth(node->next, n-1)

执行:

Javascript


输出:

Element at index 3 is 4

时间复杂度: O(n)

有关详细信息,请参阅有关编写函数以获取链表中第 N 个节点的完整文章!