Deprecated: strpos(): Passing null to parameter #1 ($haystack) of type string is deprecated in /www/wwwroot/phxin.top/usr/themes/Joe/public/config.php on line 19

Deprecated: strpos(): Passing null to parameter #1 ($haystack) of type string is deprecated in /www/wwwroot/phxin.top/usr/themes/Joe/public/config.php on line 20

Deprecated: strpos(): Passing null to parameter #1 ($haystack) of type string is deprecated in /www/wwwroot/phxin.top/usr/themes/Joe/public/config.php on line 21

Deprecated: strpos(): Passing null to parameter #1 ($haystack) of type string is deprecated in /www/wwwroot/phxin.top/usr/themes/Joe/public/config.php on line 22

Deprecated: strpos(): Passing null to parameter #1 ($haystack) of type string is deprecated in /www/wwwroot/phxin.top/usr/themes/Joe/public/config.php on line 23
顺序链表 - Hello World

顺序链表

清歌
2023-09-27 / 0 评论 / 0 阅读 / 正在检测是否收录...

顺序链表

ps:⭐注意第i个元素对应在数组中应该是data[i-1],这是因为数组的初始值是data[0],但是对应的是第一个元素⭐

顺序表的定义(动态分配方式)--malloc与free函数

#include <stdio.h>
#include <stdlib.h>
#define initsize 10
    //结构体定义
 typedef struct{    
     int *data;
     int maxsize;
     int length;
 }seqlist;
     //初始化顺序表
 void initlist(seqlist *l)    
 {
     l->data=(int *)malloc(initsize*sizeof(int));
     l->length=0;
     l->maxsize=initsize;
 }
    //顺序表动态分配
 void increasesize(seqlist *l,int len)
 {
     int *p=l->data;
             //⭐这里使用malloc函数进行动态内存申请⭐//
     l->data=(int *)malloc((l->maxsize+len)*sizeof(int));
     for(int i=0;i<l->length;i++)
     {
         l->data[i]=p[i];
     }
     l->maxsize=l->maxsize+len;
             //⭐这里使用free函数进行内存释放⭐//
     free(p);
 }
  int main()
  {
      seqlist l;
      initlist (&l); 
      for(int i=0;i<initsize;i++){
          //scanf()
      }
      increasesize(&l,5);
      return 0;
   } 

顺序链表的数值插入

顺序链表的数值插入

//顺序表数据插入
 bool listinsert(seqlist *l,int i,int element) //在顺序表L的第i个位置插入数据element 
 {
     if (i<1||i>l->length+1)//判断位置i是否越界 
     return false;
         //⭐除了判断是否越界,还需要判断是否顺序表已经存满,最开就忘记了⭐//
              if(l->length>=l->maxsize)
             return false;
         //⭐讲数据一个一个向后移动,注意是从最后一个开始⭐//
     for(int j=l->length+1;j>==i;j--)
     {
     l->data[j]=l->data[j-1];    
      } 
      l->data[i-1]=element;
      l->length++;
      return ture;
  } 

顺序表的数值删除

顺序链表的数值删除

 //顺序表数据删除
  bool listdelte(seqlist *l,int i,int elment)//删除顺序表l的第i个元素并通过elment返回删除值 
  {
      if (i<0||i>l->length)//判断位置i是否越界 
      return false;
      //if (i)   感觉应该添加一个空链表判断 
      elment=l->data[i-1];
      for (int j=i;j<l->length;j++)
      {
          l->data[j]=l->data[j+1];
      }
      l->length--;
      return 0;
   } 

顺序表的按值查询

  //顺序表按值查找
 int listfind(seqlist *l,int elment)//在顺序表l中查找第一个元素值等于elment的元素,返回其序号 
  {
      for(int j=0;j<l->length;j++)
      {
          if(l->data[j]==elment)
          return j+1;//⭐注意这里返回的是第几个元素,data[0]对应第1个元素⭐//
      }
   } 
0

评论 (0)

取消