在链表中插入和删除结点

#include<stdio.h>
#include<stdlib.h>
#define N 5
typedef struct node
{
int data;
struct node *next;
}sn;
sn *createlist(int a[])
{
sn *h;
sn *p,*q;
int i;
q=(sn *)malloc(sizeof(sn));
h=q;
for(i=0;i<N;i++)
{
p=(sn *)malloc(sizeof(sn));
p->data=a[i];
q->next=p;
q=p;
}
q->next=0;
return h;
}
void outlist(sn *h)
{
sn *p;
p=h->next;
while(p)
{
printf("%d",p->data);
p=p->next;
}
}
void destroylist(sn *h)
{
sn *p,*q;
p=h->next;
while(p)
{
q=p->next;
free(p);
p=q;
}
free(h);
}
void insert(sn *h,int a,int d)
{
sn *p,*q,*s;
s=(sn *)malloc(sizeof(sn));
s->data=d;
q=h;
p=h->next;
while(p)
{
if(p->data==a) break;
q=p;
p=p->next;
}
s->next=q->next;
q->next=s;
}
void delet(sn *h,int a)
{
sn *p,*q;
q=h;
p=h->next;
while(p)
{
if(p->data==a) break;
q=p;
p=p->next;
}
if(p)
{
q->next=p->next;
free(p);
}
}
main()
{
int a[N]={19,15,12,18,11};
sn *head;
head=createlist(a);
printf("原链表为:\n");
outlist(head);


insert(head,18,17);
printf("\n插入结点后的链表为:\n");
outlist(head);


delet(head,15);
printf("\n删除结点后的链表为:\n");
outlist(head);
printf("\n");


destroylist(head);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值