>  기사  >  백엔드 개발  >  연결리스트의 길이를 구하는 C 프로그램

연결리스트의 길이를 구하는 C 프로그램

PHPz
PHPz앞으로
2023-09-07 19:33:01993검색

연결된 목록은 동적 메모리 할당을 사용합니다. 즉, 그에 따라 메모리가 늘어나고 줄어듭니다. 이는 노드 모음으로 정의됩니다. 여기서 노드는 데이터와 링크라는 두 부분으로 구성됩니다. 데이터, 링크, 연결리스트는 다음과 같이 표현됩니다. -

연결리스트의 길이를 구하는 C 프로그램

연결리스트의 종류

연결리스트에는 다음과 같이 4가지 종류가 있습니다. -

  • 단일 연결리스트/단일 연결리스트
  • 이중/양방향 연결 list
  • Cycle Single Linked List
  • Cycle Double Linked List

재귀적 방법을 사용하여 연결리스트의 길이를 구하는 논리는

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

Program

다음은 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); } }

Output

위 프로그램이 실행되면 다음과 같은 결과가 생성된다. 결과-

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제