Implementation of Important Data Structures

file-download
1KB
file-download
800B

sequence.h ( where we store all our funct declarations, and struct def) sequence.c ( funct defs)
//
//sequence.h
//contains the structure definition as well as the headers/prototypes/declarations of
// the functions
//

struct Sequence{
	int size; // How many items are in use?
	int *theArray; 
	int cap; // How many items can maximumally hold
};
struct Sequence emptySeq();

int size(struct Sequence s);
void add (struct Sequence *s, int e);
void remove(struct Sequence *s);
int index(struct Sequence s, int i);
void freeSeq(struct Sequence *s);
//they ALL pointers because of the call-by-value property of C.
//WE ARE changing stuff in these sequences, and we want them to stick
//hence we want the pointer to the memory that has the desired sequence 
//and change them with lvalue deferences :O
//we see size and index, don't have it, cause call-by-value doesn't affect
//functionality or not.


c


#include "sequence.h"
struct SeqImpl{
int size, *theArray, cap;
};

const int limit = 10;
Sequence emptySeq(){
Sequence res = malloc(sizeof(struct SeqImpl));
// think that's there since cannot get from .h? as linking step is after compile?
res->size=0;
res->theArray = malloc(limit * sizeof(int));
res->cap = limit;
return res;
}

int size(Sequence s){
return s->size;
}
//...
//
//
//
void add(Sequence s, int e){

//push
if(s->size == cap){
//too big?i
printf("cant it full");
printf("\n jk no we ballin");
s->theArray = realloc(s->theArray, 2*cap*sizeof(int));
s->cap = 2*cap;
}
// access and set in O(1)
// baby

(s->theArray)[s->size++]=e;
}
void remove(Sequence s){
//pop
if((s->size)==0){
print("oi no doing that");
}
(s->size)--;
}





void freeSeq(Sequence s){
free(s->theArray);
//able to do this to clear entire array since contiguous, which
//may not be the case for linked lists.
free(s);
}

int main(){

Sequence s = emptySeq();
s->size = 100; //this errors since we don't know s's structure.
	      
freeSeq(s);
}
// note none of the ADT Operations consume pointers, because type Sequence is 
// already a pointer—PREVENTING clients from accessing the internals.
// but nothings preventing clients from redefining a structure Sequence ( with similar defs,
// doesn't have to be same ), within main.c.
// yea true, but datz all we can do?






Last updated