查詢連結串列長度的 C 語言程式


連結串列使用動態記憶體分配,即它們會根據需要進行增長和收縮。它們被定義為一組節點。在此,節點有兩個部分,分別是資料和連結。下面給出資料、連結和連結串列的表示:

連結串列型別

連結串列有四種類型,如下所示:

  • 單鏈表
  • 雙鏈表
  • 迴圈單鏈表
  • 迴圈雙鏈表

我們用來透過遞迴方法查詢連結串列長度的邏輯是:

int length(node *temp){
   if(temp==NULL)
      return l;
   else{
      l=l+1;
      length(temp->next);
   }
}

程式

以下是查詢連結串列長度的 C 語言程式:

 線上演示

#include <stdio.h>
#include <stdlib.h>
typedef struct linklist{
   int data;
   struct linklist *next;
}node;
int l=0;
int main(){
   node *head=NULL,*temp,*temp1;
   int len,choice,count=0,key;
   do{
      temp=(node *)malloc(sizeof(node));
      if(temp!=NULL){
         printf("
enter the elements in a list : ");          scanf("%d",&temp->data);          temp->next=NULL;          if(head==NULL){             head=temp;          }else{             temp1=head;             while(temp1->next!=NULL){                temp1=temp1->next;             }             temp1->next=temp;          }       }else{          printf("
Memory is full");       }       printf("
press 1 to enter data into list: ");       scanf("%d",&choice);    }while(choice==1);    len=length(head);    printf("The list has %d no of nodes",l);    return 0; } //recursive function to find length int length(node *temp){    if(temp==NULL)       return l;    else{       l=l+1;       length(temp->next);    } }

輸出

在執行以上程式時,它會產生以下結果:

Run 1:
enter the elements in a list: 3
press 1 to enter data into list: 1
enter the elements in a list: 56
press 1 to enter data into list: 1
enter the elements in a list: 56
press 1 to enter data into list: 0
The list has 3 no of nodes
Run 2:
enter the elements in a list: 12
press 1 to enter data into list: 1
enter the elements in a list: 45
press 1 to enter data into list: 0
The list has 2 no of nodes

更新時間:2021 年 3 月 26 日

2K+ 瀏覽量

開啟你的 職業生涯

完成該課程並獲得認證

開始學習
廣告
© . All rights reserved.