单链表的几种操作

/*任意输入5个数据测试*/

#include<stdio.h>
#include<malloc.h>
struct node
{
int date;
struct node *next;
};


/*插入函数*/
void Insert(struct node *head,int a,int b)
{
    struct node *q,*p;
    q=head->next;
    while(q!=NULL)
    {
        if(q->date==a)
   {
       p=(struct node*)malloc(sizeof(struct node));
       p->date=b;
       p->next=q->next;
       q->next=p;
           break;
   }
   q=q->next;
    }
}


/*删除函数*/
void Delete(struct node *head,int a)
{
    struct node *q,*temp;
    q=head->next->next;
temp=head->next;
if(temp->date==a)
{
   head->next=q;
   return ;
}
while(q!=NULL)
{
   if(q->date==a)
   {
       temp->next=q->next;
       break;
   }
   q=q->next;
   temp=temp->next;
}
}


/*取数函数*/
int Get(struct node *head,int x)
{
   int i=1;
   struct node *q;
   q=head->next;
   while(q!=NULL)
   {
       if(i==x)
       return q->date;
       q=q->next;
       i++;
   }
   printf("不存在这个数!\n");
   return 0;
}


/*逆置函数*/
void Reverse(struct node *head)
{
    struct node *q,*temp;
    q=head->next;
    head->next=NULL;
    while(q)
    {
        temp=q->next;   //暂存下一结点
        q->next=head->next;   //把当前节点插入到head节点后面
        head->next=q;
        q=temp;        //移动至下一节点
    }
}


/*输出函数*/
void Print(struct node *head)
{
    struct node *q;
    q=head->next;
    while(q!=NULL)
    {
        printf("%d ",q->date);
        q=q->next;
    }
    printf("\n");
}




int main()
{
int i,x,y,t,m;
struct node *head,*p,*q,*temp;
q=head=(struct node*)malloc(sizeof(struct node));
// head->next=NULL;    //前面插入
    printf("请输入要测试的数据:\n");
for(i=0;i<5;i++)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p->date);
// p->next=q->next;           //在前面插入
//    q->next=p;


        p->next=NULL;    //后面
q->next=p;      // 在后面插入
q=p;
}
printf("输入的一系列数据为:");
Print(head);
printf("\n请输入要插入的数的前一位以及要插入的数:");
scanf("%d%d",&x,&y);
Insert(head,x,y);
printf("这组数据变为:");
Print(head);
printf("\n请输入要查找的编号:");
scanf("%d",&t);
if(Get(head,t))
printf("找到这个数为:%d\n",Get(head,t));
printf("请输入要删除的数:");
scanf("%d",&m);
Delete(head,m);
printf("这组数据变为:");
Print(head);
printf("\n单链表逆置为:\n");
Reverse(head);
Print(head);
printf("\n");
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值