單鏈表(頭插法,尾插法創建,順序輸出鏈表,並返回鏈表長度)


單鏈表(頭插法,尾插法創建,順序輸出鏈表,並返回鏈表長度)

代碼如下:

#include <stdio.h>
#include <stdlib.h>
#define LENG sizeof(struct node)//結點所占單元數

struct node{
  int data;
  struct node *next;

};

int main()
{
  struct node*create1();/*尾插法建立單鏈表*/
  struct node*create2();//頭插法建立單鏈表
  int length(struct node*head);//返回單鏈表的長度,並輸出各節點的值
  struct node*head1,*head2;
  head1=create1();
  head2=create2();
  int leng1=length(head1);
  printf("\n");
  printf("單鏈表1的長度為:%d",leng1);
  printf("\n");
  int leng2=length(head2);
  printf("\n");
  printf("單鏈表2的長度為:%d",leng2);

 


return 0;
}

struct node *create1(){
  struct node*head,*tail,*p;
  int e;
  head=(struct node *)malloc(LENG);//生成表頭結點
  tail=head; //尾指針只想表頭
  printf("please input a integer number:");
  scanf("%d",&e); //輸入第一個數
  while(e!=0){
  p=(struct node *)malloc(LENG);//生成新節點
  p->data=e;
  tail->next=p; //新節點鏈接到表尾
  tail=p; //尾指針指向新節點
  printf("please input a integer number:");
  scanf("%d",&e);
}
tail->next=NULL; //尾節點的next域置為空指針
return head; //返回頭指針

}
struct node *create2(){
  struct node *head,*p;
  int e;
  head=(struct node*)malloc(LENG);
  head->next=NULL;
  printf("please input a integer number:");
  scanf("%d",&e);
  while(e!=0){
  p=(struct node *)malloc(LENG);
  p->data=e;
  p->next=head->next;
  head->next=p;
  printf("please input a integer number:");
  scanf("%d",&e);

}
return head;
};

int length(struct node*head){
int leng=0;
struct node*p;
p=head->next; //p指向首結點
while(p!=NULL){
printf("%d",p->data);
printf(" ");
leng++;
p=p->next;
}
return leng;

 

}

 

 

 

 

 

 

 

運行結果:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM