簡單鏈表的實現和輸出

實現原理:指針

用malloc動態獲取空間 ,須要的時候再獲取,節省內存,也能夠free掉,比較自由。code

首先須要3個指針,一個用來指向鏈首(*head),一個用來指向新開闢節點(*p1),一個用來指向鏈尾(*p2)。內存

首先head指針指向NULL,p1和p2都指向新開闢的節點:(新開闢節點由p1牽引)get

當獲取的節點有效io

{   第一個獲取的節點則head指向第一個節點。當不是第一個節點時則p2->next指向這個節點,而後p2=p1.(p2後移,保證p2指向最後一個節點。)class

    p1繼續開闢新節點,進入二次循環。原理

}循環

完整代碼:float


#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct Student)
struct Student
{
       int num;
       float score;
       struct Student *next;
};
int n;
struct Student *creat(void)
{
       struct Student *head;
       struct Student *p1,*p2;
       n=0;
       p1=(struct Student*)malloc(LEN);
       //p1=p2;
       scanf("%d%f",&p1->num,&p1->score);
       head=NULL;
       while(p1->num!=0)
       {
                        n=n+1;
                        if(n==1)head=p1;
                        else
                        p2->next=p1;
                        p2=p1;
                        p1=(struct Student *)malloc(LEN);
                        scanf("%d%f",&p1->num,&p1->score);
       }
       p2->next=NULL;
       return (head);
       
}

main()
{
      struct Student *pt;//define a point 
      printf("running type:ok\n");
      pt=creat();//get the head of link
      printf("program type:ok\n");
      if(pt!=NULL)
      do{
      printf("\n%d\t%f",pt->num,pt->score);
      pt=pt->next;
      }while(pt!=NULL);
      printf("\nall is:ok!\n");
      system("pause");
      return 0;
}
相關文章
相關標籤/搜索