新建链表(前插法后插法)

#include
#include

typedef struct LNode
{
char data;
struct LNode *next;


}LNode, *Linklist;


void qiancha(Linklist &head, int n);
void houcha(Linklist &head, int n);
void printl(Linklist p);
void freebuffer(Linklist head);


void main()
{
Linklist la, lb;

puts("前插法建立链表:\n");
qiancha(la, 10);
printl(la);
printf("\n");
freebuffer(la);
_CrtDumpMemoryLeaks();
puts("后插法建立链表:\n");
houcha(lb, 10);
printl(lb);


freebuffer(lb);


system("pause");


}


void qiancha(Linklist &head, int n)
{
Linklist p;
int i, c;


head = (Linklist)malloc(sizeof(LNode));
head->next = NULL;


printf("input %d numbers:\n",n);
for (i = 0; i < n; i++)
{
p = (Linklist)malloc(sizeof(LNode));
c = getchar();
p->data = c;
p->next = head->next;
head->next = p;
}
fflush(stdin);
}


void houcha(Linklist &head, int n)
{
Linklist p, q;
int i, c;


head = (Linklist)malloc(sizeof(LNode));
head->next = NULL;
q = head;


printf("input %d numbers:\n",n);
for (i = 0; i < n; i++)
{
p = (Linklist)malloc(sizeof(LNode));
c = getchar();
p->data = c;
p->next = q->next;
q->next = p;
q = p;
}
}


void printl(Linklist p)
{
int i;


i = 1;
p = p->next;
while (p != NULL)
{
printf("the %d data is %c\n", i, p->data);
i++;
p = p->next;
}
}




void freebuffer(Linklist head)
{
    Linklist temp;


while (head->next)
{
temp = head;
head = head->next;
free(temp);
}
free(head);
}

你可能感兴趣的:(新建链表(前插法后插法))