📌  相关文章
📜  Javascript程序检查给定链表的长度是偶数还是奇数

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

Javascript程序检查给定链表的长度是偶数还是奇数

给定一个链表,任务是创建一个函数来检查链表的长度是偶数还是奇数。
例子:

Input : 1->2->3->4->NULL
Output : Even

Input : 1->2->3->4->5->NULL
Output : Odd

方法一:对代码进行线性计数
遍历整个 Linked List 并不断计算节点数。一旦循环完成,我们就可以检查计数是偶数还是奇数。你可以自己试试。
方法 2:一次步进 2 个节点
方法:

1. Take a pointer and move that pointer two nodes at a time
2. At the end, if the pointer is NULL then length is Even, else Odd.
Javascript

// JavaScript program to check length 
// of a given linklist 
// Defining structure
class Node 
{
    constructor() 
    {
        this.data = 0;
        this.next = null;
    }
}
  
// Function to check the length of 
// linklist
function LinkedListLength(head) 
{
    while (head != null && 
           head.next != null) 
    {
        head = head.next.next;
    }
    if (head == null)
        return 0;
    return 1;
}
  
// Push function
function push(head, info) 
{
    // Allocating node
    node = new Node();
  
    // Info into node
    node.data = info;
  
    // Next of new node to head
    node.next = (head);
  
    // head points to new node
    (head) = node;
}
  
// Driver code
head = null;
  
// Adding elements to Linked List
push(head, 4);
push(head, 5);
push(head, 7);
push(head, 2);
push(head, 9);
push(head, 6);
push(head, 1);
push(head, 2);
push(head, 0);
push(head, 5);
push(head, 5);
var check = LinkedListLength(head);
  
// Checking for length of linklist
if (check == 0) 
{
    document.write("Odd");
} 
else
{
    document.write("Even");
}
// This code is contributed by umadevi9616
Odd


输出:

Odd

时间复杂度: O(n)
空间复杂度: O(1)

有关详细信息,请参阅检查给定链表的长度是偶数还是奇数的完整文章!