C 语言中链表的基本操作(表头插入及其逆操作)
最编程
2024-06-11 12:19:50
...
#include <stdio.h>
#include <malloc.h>
typedef struct Node
{
char data;
struct Node *next;
}SN;
SN * create(int n)
{
int i;
SN *h,*p;
h = NULL;
for(i = 0; i<n; i++)
{
p=(SN*)malloc(sizeof(SN));
printf("请输入第%d个字符:",i+1);
p->data = getchar();
fflush(stdin);
p->next = h;
h=p;
}
return h;
}
SN * def(SN * h)
{
SN * n1, *n2;
n1 = h;
n2 = NULL;
while(n1 != NULL)
{
SN *temp;
temp = n1;
n1 = n1->next;
temp->next = n2;
n2 = temp;
}
h = n2;
return h;
}
void visit(SN * h)
{
while(h != NULL)
{
printf("%c", h->data);
h = h->next;
}
printf("\n");
}
void freelist(SN *h)
{
SN *temp = h;
SN *del;
while (temp != NULL) {
del = temp;
temp = temp->next;
free(del);
}
}
int main()
{
int n;
SN *h;
printf("请输入字符个数:\n");
scanf("%d", &n);
fflush(stdin);
h = create(n);
printf("链表创建成功,对其遍历\n");
visit(h);
printf("链表逆置成功,对其遍历\n");
h = def(h);
visit(h);
freelist(h);
return 0;
}
上一篇: (链表)-反向链表(递归和标题插入实现)
下一篇: 数据结构]单链表基本操作的 C 语言实现