線性表

一、線性表可分爲順序表和鏈表

順序表:邏輯相鄰,物理也相鄰

鏈表:邏輯相鄰但物理可能不相鄰

在seqlist.h這個頭文件裏:

#pragma once //防止頭文件被重複引用
//固定長度的順序表
#define SIZE 10 //順序表的長度

typedef struct SeqList
{
 int elem[SIZE];//存放數據的數組
 int length;//有效數據的個數
}SeqList,*PSeqList;


接着,在seqlist.cpp這個文件裏:

#include  <stdio.h>
#include <assert.h>
#include "seqlist.h"   //一定要記得引用外來的這個

void InitSeqList(PSeqList ps)
{
 assert(ps != NULL);
 if(ps == NULL)
 {
  return ;
 }

 ps->length = 0;
}

static bool IsFull(PSeqList ps)//內部函數
{
 return ps->length == SIZE;
}

bool Insert(PSeqList ps,int pos,int val)
{
 if(pos<0 || pos>ps->length || IsFull(ps))//判斷不合法的pos值
 {
  return false;
 }

 for(int i=ps->length-1;i>=pos;i--)//向後移動數據
 {
  ps->elem[i+1] = ps->elem[i];
 }
 ps->elem[pos] = val; //將新的值插入

 ps->length++;  //修改有效數據個數
 
 return true;
}

int Search(PSeqList ps,int key)
{
 for(int i=0;i<ps->length;i++)
 {
  if(ps->elem[i] == key)
  {
   return i;
  }
 }
 return -1;
}

bool DeleteVal(PSeqList ps,int key)
{
 int index = Search(ps,key);
 if(index < 0)
 {
  return false;
 }
 /*for(int i=index;i<ps->length-1;i++)
 {
  ps->elem[i] = ps->elem[i+1];
 }

 ps->length--;

 return true;*/
 return DeletePos(ps,index);
}

bool DeletePos(PSeqList ps,int pos)
{
 if(pos<0 || pos>=ps->length)//
 {
  return false;
 }

 for(int i=pos;i<ps->length-1;i++)
 {
  ps->elem[i] = ps->elem[i+1];
 }

 ps->length--;

 return true;
}

int GetLength(PSeqList ps)
{
 return ps->length;
}

bool IsEmpty(PSeqList ps)
{
 return ps->length == 0;
}

void Clear(PSeqList ps)//SeqList *ps
{
 ps->length = 0; //(*ps).length = 0;,[],->
}

void Destroy(PSeqList ps)
{
 Clear(ps);
}

void Show(PSeqList ps)
{
 for(int i=0;i<ps->length;i++)
 {
  printf("%d ",ps->elem[i]);
 }
 printf("\n");
}

//rtval:輸出參數
bool GetElem(PSeqList ps,int pos,int *rtval)
{
 if(pos<0 || pos>=ps->length)
 {
  return false;
 }
 *rtval = ps->elem[pos];

 return true;
}

測試用例:

int main()
{
Node head;//
InitList(&head);
for(int i=0;i<16;i++)
{
//Insert_head(&head,i);
Insert_tail(&head,i);//0 1 2 3 4 5
}


Insert_head(&head,1);
Insert_head(&head,2);
Insert_head(&head,3);
Insert_head(&head,4);


Show(&head);
//Reverse(&head);
//Show(&head);
Unique(&head);
Show(&head);


/*int val;
GetElem(&head,3,&val);
printf("%d\n",val);*/


Destroy(&head);
Destroy(&head);


return 0;
}




/*


#include <string.h>


int main()
{
printf("");


strlen("abc");
return 0;
}
*/
/*
struct Node
{
int data;
int *next;
};


int main()
{
Node na = {1,NULL};//
Node nb = {2,NULL};
Node nc = {3};


na.next = &nb.data;//int *,nb


na.next


return 0;
}
*/




#include "dseqlist.h"


int main()
{
DSeqList ds;//12
InitSeqList(&ds);
for(int i=0;i<15;i++)
{
Insert(&ds,i,i);
}


Show(&ds);


return 0;
}




/*
#include "seqlist.h"


int main()
{
SeqList s;//44
InitSeqList(&s);
for(int i=0;i<15;i++)
{
Insert(&s,i,i);
}
Show(&s);


return 0;
}
*/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章