c语言实现单链表的创建,遍历,插入,删除,反转函数

#include<stdio.h>
#include <stdio.h>
#include<stdlib.h>
int num=0;
struct list{
    int val;
    struct list*next;
}; 
//创建链表函数
struct list* creat()
{
    struct list* head,p;
    struct list*q;//q为前,p为后 
    head=NULL;
    printf("想创建的结点的个数:");
    
    scanf("%d",&num);
    for(int i=0;i<num;i++)
    {
        int val;
        printf("请输入第%d个节点的值:",i+1);
        scanf("%d",&val);
      struct list *p=(struct list*)malloc(sizeof(struct list));
      p->val=val;
      p->next=NULL;
      if(head==NULL)//判断是否为第一个节点,如果是头指针指向当前节点 
      {
          head=p;
      }
      else{
          q->next=p;//将新创建的指针p连接到当前指针上 
      }
      q=p;//使q也移动到当前节点 
    }
    return head;
}

//打印链表函数
 void travel(struct list* head)
{
    struct list *p=head;
    while(p!=NULL)
    {
        printf("%d ",p->val);
        p=p->next;
    }
 } 
 //插入函数
 
 struct list* insert(struct list* head) {
    int n;int m; int flag=0;
    while(flag==0) 
    {
    printf("请输入要插入在第几个数之后:\n");
    scanf("%d",&m);
    if(m>num)
    {
        printf("插入失败,请重新输入:");
        flag=0;
     } 
     else
     flag=1;
     }
     printf("请输入要插入的数值:\n");
    scanf("%d",&n);
    struct list* p = head;
struct     list* s = (struct list*)malloc(sizeof(struct list));
    
    s->val = n;
    for (int i = 1; i < m; ++i) {
        p = p->next;
    }
    
    s->next = p->next;
    p->next = s;
    return head;
}
//删除函数
struct list* delete(struct list* head)
{
    int m; 
printf("请输入要删除第几个数的位置:\n");
    scanf("%d",&m);
    
    struct list* p = (struct list*)malloc(sizeof(struct list));
    p = head;
    for(int i = 2; i < m; ++i)
    {
        p = p->next;
    }
if(m>num)
{
printf("删除失败");
return 0;
}
    p->next=p->next->next;
    return head;
}
//反转函数
struct list* resever(struct list*head)
{


struct list* n1 = (struct list*)malloc(sizeof(struct list));
struct list* n2 = (struct list*)malloc(sizeof(struct list));
struct list* n3= (struct list*)malloc(sizeof(struct list));
n1=NULL;
n2=head;
n3=head->next;

if(head=NULL)
return NULL;

while(n2)
{
//反转
n2->next=n1;
//迭代移动
n1=n2;
n2=n3;
if(n3)
n3=n3->next;
}

return n1;
}

int main()
{
    struct list *node;
    node=creat();
    node=resever(node);
    travel(node);
    
}
    

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北月殇晨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值