获取链表长度(迭代法和递归法)
迭代法
1、设定一个计数器,初始值为0
2、初始化current到头节点
3、如果current不为null进行以下循环
a) current = current -> next b) count++;
4、返回计数器
c语言:
/* Counts no. of nodes in linked list */
int getCount(struct Node* head)
{
int count = 0; // Initialize count
struct Node* current = head; // Initialize current
while (current != NULL)
{
count++;
current = current->next;
}
return count;
}
java:
/* Returns count of nodes in linked list */
public int getCount()
{
Node temp = head;
int count = 0;
while (temp != null)
{
count++;
temp = temp.next;
}
return count;
}
c#:
/* Returns count of nodes in linked list */
public int getCount()
{
Node temp = head;
int count = 0;
while (temp != null)
{
count++;
temp = temp.next;
}
return count;
}
递归法
int getCount(head) 1) If head is NULL, return 0. 2) Else return 1 + getCount(head->next)
c语言:
/* Counts the no. of occurrences of a node
(search_for) in a linked list (head)*/
int getCount(struct Node* head)
{
// Base case
if (head == NULL)
return 0;
// count is 1 + count of remaining list
return 1 + getCount(head->next);
}
java
/* Returns count of nodes in linked list */
public int getCountRec(Node node)
{
// Base case
if (node == null)
return 0;
// Count is this node plus rest of the list
return 1 + getCountRec(node.next);
}
c#
/* Returns count of nodes in linked list */
public int getCountRec(Node node)
{
// Base case
if (node == null)
return 0;
// Count is this node plus rest of the list
return 1 + getCountRec(node.next);
}
文章来源:https://www.geeksforgeeks.org/find-length-of-a-linked-list-iterative-and-recursive/
本博客文章绝大多数为原创,少量为转载,代码经过测试验证,如果有疑问直接留言或者私信我。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。
创作文章不容易,转载文章必须注明文章出处;如果这篇文章对您有帮助,点击右侧打赏,支持一下吧。