C语言实现单链表的增删改查

#include
#include

typedef struct node
{
int data;
struct node *next;
}node;
node *head;
int k;

node * creates()
{
node *p,*s,*h;
int j=1,x, n;
p=h=(node*)malloc(sizeof(node));
h->next=NULL;
printf("请输入链表长度:\n");
scanf("%d",&n);
printf("请输入%d 个数字创建链表:\n",n);
while(j<=n)
{
scanf("%d",&x);
s=(node*)malloc(sizeof(node));
s->data=x;
p->next=s;
p=s;
j++;
}
p->next=NULL;
return h;
}


void insertsl(node *head, int k, int i)
{
int j;
node *p, *t;
p=head;
j=0;
while ( p&&j{
p = p->next;
j++;
}
if (!p||j>k-1)
{
printf("插入位置不对。\n");
}
t=(node *)malloc (sizeof (node));
t->data=i;
t->next=p->next;
p->next=t;

}


void deletesl(node *h,int i)
{
node *p,*s,*q;
int j=1;
p=h;
while(p->next!=NULL)
{
q=p->next;
if(q->data==i)
break;
p=p->next;
j++;
}
if(p->next==NULL)
{
printf("找不到你要删除的元素\n");
return;
}
else
{
s=p->next;
p->next=s->next;
free(s);
printf("在位置%d成功删除%d\n",j,i);
}
}

node *lianjie(node *L1,node *L2)
{
node *p1, *p2;
p1=L1;
p2=p1->next;
while(p2->next!=NULL)
{
p2=p2->next;
}
p2->next=L2->next;
return p1;
}

void hebing (node *L)

{
node *s,*t,*r;
s=L->next;
while(s)
{
t=s;
r=s->next;
while(t->next)
{
if(s->data==r->data)
{
t->next=r->next;
r=t->next;
}
else
{
t=t->next;
r=r->next;
}
}
s=s->next;
}
}

void print(node *h)
{
printf("\n链表中的元素为");
node *s;
s=h->next;
if(s!=NULL)
{
while(s!=NULL)
{
printf(" %d ",s->data);
s=s->next;
}
}
else
{
printf("这是一个空表%d");
}
printf("\n");
}

int main()
{
node *p,*q,*r,*s;
int a,b;
char c;
p=creates();
while(1)
{
printf("\n请输入你要插入的元素的位置:\n");
scanf("%d",&b);
printf("\n请输入你要插入的元素:\n");
scanf("%d",&a);
insertsl(p,b,a);


printf("\n你还要插入其他元素吗?请选择(Y:是|N:否):\n");

c=getch();

printf("%c",c);

if(c!='Y'&& c!='y')
{
break;
}
}

print(p);
printf("\n你想要删除的元素是:\n");
scanf("%d",&a);
deletesl(p,a);
print(p);
q=creates();

r=creates();
s= lianjie(q,r);
hebing(s);
print(s);
printf("谢谢使用!");
return 0;
}

相关文档
最新文档