判定链表长度是奇数还是偶数
[!Tip]
本节源代码见Github链接🔗
问题描述
检查链表的结点数是奇数还是偶数
核心思路
定义一个指向链表头结点,每次向后移动两个结点的指针。若移动到最后,指针指向NULL,则说明链表结点数是偶数;若它指向尾结点,则说明链表结点数是奇数。
实现代码
【👉🏻>>点击展开查看代码】
/**
* 判断链表结点数是否为偶数
*
* @param headNode
* @author: Max Solider
* @date: 2022/10/9 14:18
*/
boolean isLinkedListLengthEven(NormalListNode headNode) {
if (headNode == null) {
System.out.println("The length of linked list is even");
return true; }
NormalListNode ptr = headNode;
while (ptr != null) {
if (ptr.getNext() == null) {
System.out.println("The length of linked list is not even");
return false; }
ptr = ptr.getNext().getNext();
}
System.out.println("The length of linked list is even");
return true;
}
时间复杂度
时间复杂度为O(n),用于遍历链表。
空间复杂度
空间复杂度为O(1),用于存储临时变量。