链表及链表嵌套的操作


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

typedef struct childLink
{
char nm[100];
struct childLink *next;
}CHILDNODE;

typedef struct linkTable
{
int birthYear;
CHILDNODE *mz;
struct linkTable *next;
}LINKNODE;

LINKNODE * insert(LINKNODE *head, LINKNODE *input);
CHILDNODE * insert_nm(CHILDNODE *head_c, CHILDNODE *input_nm);
void print(LINKNODE *head);

/************************************************************************/
/* main
/************************************************************************/
void main()
{
LINKNODE *head, *input;
CHILDNODE *head_c, *input_c;
head = NULL;
head_c = NULL;

while(1)
{
if ((input=(LINKNODE *)malloc(sizeof(*input))) == NULL)
{
printf("malloc fail!");
exit(0);
}

printf("input birthYear(0:quit):\n");
scanf("%d", &input->birthYear);

if (input->birthYear == 0)
{
break;
}

while(1)
{
if ((input_c=(CHILDNODE *)malloc(sizeof(*input_c))) == NULL)
{
printf("nm malloc fail!");
exit(0);
}

printf("input CHILDNODE:\n");
scanf("%s", &input_c->nm);

if (strcmp(input_c->nm, "0") == 0)
{
break;
}

head_c = insert_nm(head_c, input_c);
}

input->mz = head_c;
head = insert(head, input);

head_c = NULL;
}

print(head);
}

/************************************************************************/
/* insert link
/************************************************************************/
LINKNODE * insert(LINKNODE *head, LINKNODE *input)
{
LINKNODE *p0, *p1, *p2;
p0 = input;
p1 = head;

if (head == NULL)
{
head = p0;
p0->next = NULL;
}
else
{
//compare p0 with p1 to p(n-1)
while (p0->birthYear > p1->birthYear && p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}

//compare with last one
if (p0->birthYear <= p1->birthYear)
{
if (p1 == head) //top
{
head = p0;
p0->next = p1;
}
else //middle
{
p2->next = p0;
p0->next = p1;
}
}
else //end
{
p1->next = p0;
p0->next = NULL;
}
}

return head;
}

/************************************************************************/
/* insert child link
/************************************************************************/
CHILDNODE * insert_nm(CHILDNODE *head, CHILDNODE *input)
{
CHILDNODE *p0, *p1, *p2;
p0 = input;
p1 = head;

if (head == NULL)
{
head = p0;
p0->next = NULL;
}
else
{
while (strcmp(p0->nm, p1->nm)>0 && p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}

if (strcmp(p0->nm, p1->nm) < 0) { if (p1 == head) { head = p0; p0->next = p1;
}
else
{
p2->next = p0;
p0->next = p1;
}
}
else
{
p1->next = p0;
p0->next = NULL;
}

}

return head;
}

/************************************************************************/
/* print link
/************************************************************************/
void print(LINKNODE *head)
{
LINKNODE *pOut;
CHILDNODE *pOut_c;

pOut = head;

while (pOut != NULL)
{
printf("\n\nBirthYear: %d\nChild:", pOut->birthYear);

pOut_c = pOut->mz;
while (pOut_c != NULL)
{
printf(" %s", pOut_c->nm);

pOut_c = pOut_c->next;
}
pOut = pOut->next;

}
}


Comments are closed.