C语言实现顺序链表

刚上完数据结构课,链表这一块的知识居然忘记了,也上博客看了看别人写的代码,我则是根据他们的代码写了一些代码。话不多说直接上代码。
#include <stdio.h>
#include <stdlib.h>

#define EmleType int 
#define true 1
#define false 0
//顺序链表的创建
struct Node
{
   EmleType data;
   struct Node * next;
};


struct Node * CreateList()
{
EmleType n,i,x;
   struct Node * head,* tail,*L;//
   head = (struct Node*)malloc(sizeof(struct Node));
   head->next = NULL;//先建立一个带头节点的空链表
   tail = head;
   scanf("%d",&n);
   for(i=0;i<n;i++){
    L = (struct Node*)malloc(sizeof(struct Node));
    scanf("%d",&x);
    L->data = x;
    L->next = NULL;
    tail->next = L;
    tail = L;
   }
return head;
}

//获取链表中某一个元素的值
EmleType GetElem(struct Node * L,int i,EmleType *e)
{
    int j = 1;
    struct Node * p = L->next;//p指针指向第一个结点
    while(p && j < i){
    p = p->next;
     j++;	
    }
    if(!p || j > i) /*第i个元素不存在*/
	   return false;
    *e = p->data;
return true;
}

//单链表插入元素,先查找,再插入
EmleType ListInsert(struct Node * L ,EmleType i, EmleType e)
{
   EmleType j = 0;
   struct Node *p = L,* s;
   while(p && j < i-1)
    {
       p = p->next;
        j++;
    }
   if(!p || j > i-1)
       return false;
   s = (struct Node *)malloc(sizeof(struct Node));
   s->data = e;
   s->next = p->next;
   p->next = s;
return true;
}

EmleType ListDelate(struct Node * L,EmleType i)
{
   EmleType j = 0;
   struct Node * p = L ,* q;
   while(p && j < i -1)
     {
        p = p->next;
        j++;
     }
   if(!p->next || j > i-1)
     return false;
   q = p->next;
   p->next  = q->next;
   free(q);
   return true;
}



void ListOutput(struct Node * L)
{
  while(L->next!=NULL)
    {
        printf("%d ",L->next->data);
        L=L->next;
    }
}

EmleType main()
{
EmleType x,num;
  struct Node * L = CreateList();
  printf("请输入你需要获取链表的num值\n");
  scanf("%d",&num);
  if(GetElem(L,num,&x) == true)
   {
      printf("成功获得第i个元素的值\n");
       printf("%d\n",x);
       printf("当前链表为:\n");
       ListOutput(L);//输出当前链表
       printf("\n");
   }
   else
      printf("获取失败");

   if(ListInsert(L,num,9) == true)
     {
       printf("在链表的第%d个位置插入成功\n",num-1);
       printf("当前链表为:\n");
       ListOutput(L);//输出当前链表
       printf("\n");
     }
     else
      printf("插入失败");
   
   if(true == ListDelate(L,num))
     {
       printf("在链表的第%d个位置删除成功\n",num-1);
       printf("当前链表为:\n");
       ListOutput(L);//输出当前链表
       printf("\n");
     }
    else
      printf("删除失败");
return 0;
}

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值