連結清單使用動態記憶體分配,即它們相應地增長和收縮。它們被定義為節點的集合。這裡,節點有兩個部分,即資料和鏈路。資料、連結和鍊錶的表示如下-
鍊錶有四種類型,如下: -
我們用遞歸方法求鍊錶長度的邏輯是-
int length(node *temp){ if(temp==NULL) return l; else{ l=l+1; length(temp->next); } }
以下是求鍊錶長度的C程式-
現場示範
#include#include 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
以上是C程式以找到鍊錶的長度的詳細內容。更多資訊請關注PHP中文網其他相關文章!