注释说明以后再补,先给程序
#include <stdio.h>
#include <stdlib.h>
typedef struct svit
{
int x ;
struct svit *next ;
} s ;
s *add (s *hd, int m)
{
s *p = NULL, *pr = hd;
int x;
p = (s *)malloc(sizeof(s)) ;
if (p == NULL)
{
printf("error\n") ;
exit (0) ;
}
if (hd == NULL)
{
hd = p ;
}
else
{
while (pr->next != NULL)
{
pr = pr->next ;
}
pr->next = p ;
}
//printf( "输入第%d个整数:", m) ;
scanf("%d", &x) ;
p->x = x ;
p->next = NULL ;
return hd ;
}
void show (s *hd)
{
s *p = hd;
int j = 1;
while (p != NULL)
{
printf("节点:%d 数据:%d\n", j , p->x) ;
p = p->next ;
j++ ;
}
}
void up (s *hd)
{
s *p = hd , *pr = NULL;
while (p != NULL)
{
pr = p ;
p = p->next ;
free (pr) ;
}
}
s * sc (s *hd, int a)
{
s *p = hd, *pr = hd;
if (hd == NULL)
{
printf("为空表\n") ;
return (hd) ;
}
while (p->x != a && p->next != NULL)
{
pr = p ;
p = p->next;
}
if (p->x == a)
{
if (p == hd)
{
hd = p->next ;
}
else
{
pr->next = p->next ;
}
free(p) ;
}
else
{
printf("未找到\n") ;
}
return hd ;
}
s * tj (s *hd, int a)
{
s *p = hd, *pr = hd, *t = NULL;
t = (s *)malloc(sizeof(s)) ;
if (t == NULL)
{
printf("error\n") ;
exit (0) ;
}
t->x = a ;
t->next = NULL ;
if (hd == NULL)
{
hd = t ;
}
else
{
while (a > p->x && p->next != NULL)
{
pr = p ;
p = p->next ;
}
if (a <= p->x)
{
if (p == hd)
{
t->next = p ;
hd = t ;
}
else
{
t->next = p ;
pr->next = t ;
}
}
else
{
p->next = t ;
}
}
return hd ;
}
int jy (int x, int n)
{
while (x != 1)
{
while (getchar() != '\n') ;
printf("输入无效,请重新输入:\n") ;
x = scanf("%d", &n) ;
}
return n ;
}
void mu(s *hd)
{
int b, x, s;
printf("选择你想进行的操作,并输入你想进行的操作前的序号:\n1:删除节点\n2:添加节点\n3:退出程序") ;
s = scanf("%d", &b) ;
b = jy(s, b) ;
if (b == 1)
{
printf("请输入你要删除的节点数据:\n") ;
s = scanf("%d", &x) ;
x = jy(s, x) ;
show(sc(hd, x)) ;
}
else if (b == 2)
{
printf("请输入你要添加的节点数据:") ;
s = scanf("%d", &x) ;
x = jy(s, x) ;
show(tj(hd,x)) ;
}
else if (b == 3)
{
exit (0) ;
}
else
{
printf("输入无效\n") ;
mu(hd) ;
}
}
void main(void)
{
s *hd = NULL;
int n, i = 0, x = 0;
char j;
printf("输入想输入数的个数n:") ;
x = scanf("%d", &n) ;
n = jy(x, n) ;
printf("输入%d个整数:", n) ;
for ( ; i<n; i++)
{
hd = add(hd,i+1) ;
}
show(hd) ;
printf("%d个节点\n", i) ;
mu(hd) ;
up(hd) ;
}