7 查找链表的长度(迭代和递归)

这篇博客介绍了如何使用迭代和递归两种方法来计算单链表的长度。提供了C/C++的实现代码,示例中显示链表1-> 3-> 1-> 2-> 1的长度为5,并进行了代码测试验证。
摘要由CSDN通过智能技术生成

编写C函数来计算给定单链表中的节点数。

例如,对于链接列表1-> 3-> 1-> 2-> 1,该函数应返回5。

迭代解决方案

1)将计数初始化为0 
2)初始化节点指针,current = head。
3)当current不为NULL时执行以下操作
     a)current=current->next
     b)count ++;
4)返回计数 

以下是算法是C/C++实现,以查找节点数


// Iterative C program to find length or count of nodes in a linked list 
#include<stdio.h> 
#include<stdlib.h> 
  
/* Link list node */
struct Node 
{ 
    int data; 
    struct Node* next; 
}; 
  
/* Given a reference (pointer to pointer) to the head 
  of a list and an int, push a new node on the front 
  of the list. */
void push(struct Node** head_ref, int new_data) 
{ 
    /* allocate node */
    struct Node* new_node = 
            (struct Node*) malloc(sizeof(struct Node)); 
  
    /* put in the data  */
    new_node->data  = new_data; 
  
    /* link the old list off the new node */
    new_node->next = (*head_ref); 
  
    /* move the head to point to the new node */
    (*head_ref)    = new_node; 
} 
  
/* Counts no. of nodes in linked list */
int getCount(struct Node* head) 
{ 
    int count = 0;  // Initialize count 
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值