鏈表的創建與輸出

創建兩個學生鏈表,含有姓名,年齡的信息,一個鏈表存放男生,一個鏈表存放女生

並且合併這兩個鏈表。



#include <stdio.h>
#include <stdlib.h>


#define LEN sizeof (struct student)


struct student
{
char name[100];
int age;
struct student *next;
};


int n;


struct student *create ()
{


struct student *head;
struct student *p1 = NULL;
struct student *p2 = NULL;


n = 0;
p1 = (struct student *) malloc (LEN);
p2 = p1;


if (p1 == NULL)
{
printf ("Cann't create it, try it again in a monent!\n");
return NULL;
}
else
{
head = NULL;
printf ("Please input %d node -- name, year: \n",n+1);
scanf ("%s",&(p1->name));
scanf ("%d",&(p1->age));
}

while (strcmp(p1->name,"0") != 0)
{
n += 1;
if (n == 1)
{
head = p1;
p2 -> next = NULL;
}
else 
{
p2 -> next = p1;
}


p2 = p1;


p1 = (struct student *) malloc (LEN);
printf ("Please input %d node -- name,age: \n",n+1);
scanf ("%s",&(p1->name));
if (strcmp(p1->name,"0") == 0)
break;
scanf ("%d",&(p1->age));


}


p2->next = NULL;
free (p1);
p1 = NULL;
return head;
}


void printA (struct student *head)
{
struct student *p;
printf ("Now, these %d records are: \n",n);
p = head;


if (p != NULL)
{
printf ("head is %p\n",p);
while (p != NULL)
{
printf ("%p   %s   %d   %p\n", p, p->name, p->age, p->next);
p = p->next;
}
}


}

struct student *comb(struct student *b, struct student *g)
{
struct student *p = NULL;
p = b;
while (p->next != NULL)
{
p = p->next;
}
p->next = g;
return b;
}




int main()
{
struct student *boy = NULL;
struct student *girl = NULL;


boy = create ();
printA (boy);
girl = create ();
printA (girl);


printA( comb (boy,girl) );


    return 0;
}




發佈了31 篇原創文章 · 獲贊 9 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章