链表节点类型如下: typedef char datatype; struct node { datatype data; struct node *next; };
编写程序实现单向链表的建立、读取和删除函数,在主函数中选择执行。
输入用例:
5abcde
输出用例:
The content of list:abcde
The content of list:null
读取就是链表内容显示?
#include <stdio.h>
typedef char datatype;
struct node
{
datatype data;
struct node *next;
};
struct node * listCreate(int n)
{
struct node * head, *p,*q;
int i;
head = (struct node*) malloc(sizeof(struct node));
head->next = NULL;
p = head;
for(i=0;i<n;i++)
{
q = (struct node*) malloc(sizeof(struct node));
scanf("%c",&q->data);
q->next = NULL;
p->next = q;
p = q;
}
return head;
}
void showNode(struct node *head)
{
printf("The content of list:");
if(head == NULL || head->next == NULL)
{
printf("NULL\n");
return;
}
while(head->next != NULL)
{
printf("%c",head->next->data);
head = head->next;
}
printf("\n");
}
void clearList(struct node *head)
{
struct node *p = head,*q;
while(p->next != NULL)
{
q = p->next;
p->next = p->next->next;
free(q);
}
}
int main()
{
int n;
struct node * head;
scanf("%d",&n);
head = listCreate(n);
showNode(head);
clearList(head);
showNode(head);
return 0;
}
链表的基本操作,删除有什么要求吗
代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef char datatype;
struct node
{
datatype data;
struct node* next;
};
//创建
struct node* createlist()
{
struct node* head, * p, * t;
int i, n;
datatype ch;
head = (struct node*)malloc(sizeof(struct node));
head->next = 0;
p = head;
scanf("%d", &n);
for (i = 0; i < n; i++)
{
ch = getchar();
t = (struct node*)malloc(sizeof(struct node));
t->data = ch;
t->next = 0;
p->next = t;
p = t;
}
return head;
}
//遍历输出
void showlist(struct node* head)
{
struct node* p;
if (head == 0)
{
printf("The content of list:null\n");
return;
}
p = head->next;
printf("The content of list:");
while (p)
{
printf("%c", p->data);
p = p->next;
}
printf("\n");
}
//删除所有元素
struct node* deletelist(struct node* head)
{
struct node* p;
if (head == 0) return 0;
while (head)
{
p = head->next;
free(head);
head = p;
}
head = 0;
return head;
}
int main()
{
struct node* head = 0;
int op;
while (1)
{
printf("1.创建链表\n");
printf("2.删除链表\n");
printf("3.显示链表\n");
printf("4.退出程序\n");
scanf("%d", &op);
getchar(); //吸收回车符
switch (op)
{
case 1:
head = createlist();
break;
case 2:
head = deletelist(head);
break;
case 3:
showlist(head);
break;
case 4:
return 0;
}
}
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!