新手小白自己写的单链表的建立、插入、删除、输出。如果封装成不同函数应该会更加简便漂亮,我懒得改了へ(;´Д`へ)
#include <stdio.h>
#include <stdlib.h>
struct link{
int data;
struct link *next;
};
int main()
{
struct link *head;
head = (struct link*)malloc(sizeof(struct link));
head->next = NULL;
struct link *p, *q, *a, *d;
p=head;
int i;
char c;
printf("请输入数字(以0为结尾):");
i = 0; //输入
p = q = (struct link *)malloc(sizeof(struct link)) ;
scanf("%d",&p->data);
head = NULL;
while (p->data != 0)
{
i++;
if(i == 1)
head = p;
else
q->next = p;
q = p;
p = (struct link *)malloc(sizeof(struct link)) ;
scanf("%d",&p->data);
}
q->next = NULL;
printf("\n数字链表的数字为:\n"); //输出
a = head;
while(a != NULL)
{
printf("%6d",a->data);
a = a->next;
}
printf("\n请输入需插入的数值:"); //插入
int b;
scanf("%d",&b);
a = head;
while(a->next != NULL)
{
if(a->data > b) //插在第一个
{
q = (struct link *)malloc(sizeof(struct link)) ;
q->data = b;
q->next = a;
head = q;
break;
}
if(a->next->data < b) //插在中间
a = a->next;
else
{
q = (struct link *)malloc(sizeof(struct link)) ;
q->data = b;
q->next = a->next;
a->next = q;
break;
}
}
if(a->next == NULL) //插在最后
{
q = (struct link *)malloc(sizeof(struct link)) ;
q->data = b;
a->next = q;
q->next = NULL;
}
printf("\n数字链表的数字为:\n"); //输出
a = head;
while(a != NULL)
{
printf("%6d",a->data);
a = a->next;
}
printf("\n请输入要删除的数值:"); //删除
int m;
scanf("%d",&m);
a = head;
while (a->next != NULL)
{
if(a->data == m)
{
head = a->next;
free(a);
break;
}
if(a->next->data == m)
{
d = a->next;
a->next = d->next;
free(d);
break;
}
a = a->next;
}
if(a->next == NULL)
printf("未找到该数值");
printf("\n数字链表的数字为:\n"); //输出
a = head;
while(a != NULL)
{
printf("%6d",a->data);
a = a->next;
}
return 0;
}