#include<stdio.h> #include<string.h> #include<math.h> #include<stdlib.h> typedef struct node{ int data; struct node *next; }g_tNode,*g_ptNode; static g_ptNode ptHead; void AddTailNew(int num) { g_ptNode tmp,tail; tmp = ptHead; tail = malloc(sizeof(g_tNode)); tail->data = num; if(ptHead == NULL) { ptHead = tail; tail -> next = NULL; } else { while(tmp->next) { tmp = tmp->next; } tmp->next = tail; tail->next = NULL; } } void AddTail(g_ptNode *tail) { g_ptNode tmp; if(ptHead == NULL) { ptHead = *tail; (*tail)->next = NULL; } else { tmp = ptHead; while(tmp->next) { tmp = tmp->next; } tmp->next = *tail; (*tail)->next =NULL; } } //注意形参与实参的区别! 若定义成 CreateListTail(g_ptNode L,int n) ,则修改的数据不能有效的保存; // 虽然g_ptNode定义的变量是指针,但是在main函数里传递进来的参数是static g_ptNode gHead,他也是同类型的指针,那么传递给CreateListTail //的就是形参了 void CreateListTail(g_ptNode *L,int n) { int i; g_ptNode p,tmp; *L = malloc(sizeof(g_tNode)); tmp = *L; for(i=0;i<n;i++) { p = malloc(sizeof(g_tNode)); p->data = rand()%100+1; tmp->next = p; tmp =p ; } tmp ->next = NULL; } void DisplayList(g_ptNode mynode) { g_ptNode tmp; // if(!mynode->next) // { // printf("没有数据 "); // } // else { printf("数据为: "); tmp = mynode; // tmp = mynode->next; if(!tmp) { printf("没有数据 NULL: "); } while(tmp) { printf("%d ",tmp->data); tmp = tmp ->next; } } } void main() { int n=0,storeData=0; static g_ptNode gHead; g_ptNode tmp; for ( n=0; n<10; n++) { AddTailNew(n); // tmp = malloc(sizeof(g_tNode)); // tmp->data = n; // AddTail(&tmp); } DisplayList(ptHead); // CreateListTail(&gHead,10); // DisplayList(gHead); }
#include<stdio.h> #include<string.h> #include<math.h> #include<stdlib.h> typedef struct node{ int data; struct node *next; }g_tNode,*g_ptNode; static g_ptNode ptHead; void AddTail(int num) { g_ptNode tmp; g_ptNode tail; tail = malloc(sizeof(g_tNode)); tail->data =num; if(!ptHead) { ptHead = tail; tail->next =NULL; } else { tmp = ptHead; while(tmp->next) { tmp = tmp->next; } tmp->next = tail; tail->next = NULL; } } void printNode() { g_ptNode tmp; if(!ptHead) { printf("没有数据 "); } else { tmp=ptHead; while(tmp) { printf("%d ",tmp->data); tmp = tmp->next; } } } void main() { int n; // getchar(); for (n=0; n<10; n++) { AddTail(n); } printf("添加结束,开始打印 "); // getchar(); printNode(); printf("打印结束 "); }
待更新