#include<stdio.h>
#include<stdlib.h>
typedef char datatype;
struct node
{
datatype data;
struct node *next;
};
typedef struct node LNode;
LNode *AppendNode(LNode *head,datatype ch)
{
LNode *p,*pr=head;
p=(LNode*)malloc(sizeof(LNode));
if(p==NULL)
{
printf("内存分配失败!\n");
exit(0);
}
p->data=ch;
if(head==NULL)
head=p;
else
{
while(pr->next!=NULL)
{
pr=pr->next;
}
pr->next=p;
}
p->next=NULL;
return head;
}
void DeleteLink(struct node *head)
{
struct node *current = head->next;
struct node *temp = current;
while (current != NULL)
{
temp = current;
current = current->next;
free(temp);
}
head->next = NULL;
}
void output(LNode *head)
{
LNode *p;
p=head->next;
printf("The content of list:");
if(head->next==NULL)
printf("null");
else
{
while(p)
{
printf("%c",p->data);
p=p->next;
}
}
putchar('\n');
}
int main()
{
int n;
int i;
datatype ch;
LNode *head=NULL;
head=(LNode*)malloc(sizeof(LNode));
if(head==NULL)
{
printf("内存分配失败!\n");
exit(0);
}
head->next=NULL;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%c",&ch);
head=AppendNode(head,ch);
}
output(head);
DeleteLink(head);
output(head);
return 0;
}
单向链表例1
最新推荐文章于 2024-10-03 13:36:06 发布