SE250:lab-4:hlin079
function int leght
int lenght(Cons*list){ int count=0; for (;list!=nil;list=list->tail){ count++; } return count; }
function element_t nth(inti, Cons*)
element_t nth(int i,Cons*list){ int count=0; for (;list!=nil;list=list->tail){ if (i!=count){ count++; } else { break; } } return list->head; }
Equal function
int equal(Cons*list,Cons*list2){ for(;list!=nil&&list2!=nil;list=list->tail,list2=list2->tail){
if (list->head!=list2->head){
return 0; }
} if (list==list2){
return 1; } return 0; }
find function
Cons*find(element_t q,Cons*list){ for (;list!=nil;list=list->tail){
if (list->head==q){ return list; }
} return nil; }
copy function
Cons*copy_list(Cons*list){ int w= lenght(list); int i; Cons*list2; Cons*start; list2=nil; for ( i=0;i<w;i++){ list2=cons(0,list2); } start=list2; for (;list!=nil&&list2!=nil;list=list->tail,list2=list2->tail){
list2->head=list->head;
} return start; }
first of all, i setup the lenght of list2. After setup the lenght , i used for loop to put each element in the list to list2.
append function
Cons*append(Cons*list,Cons*list2){ int w= lenght (list)+lenght(list2); int i; Cons* list3; Cons*start1; list3=nil; for (i=0;i<=w;i++){
list3=cons(0,list3);
} start1=list3; for (;list!=nil&&list3!=nil;list=list->tail,list3=list3->tail){ list3->head=list->head; } for (;list2!=nil&&list3!=nil;list2=list2->tail,list3=list3->tail){ list3->head=list2->head; } return start1; }
at frist i did not set list3 to nil. also i did not have Cons*start when i run the file with the main
int main( ) { Cons*list; Cons*list2; Cons*both; print_list(list= cons(1,cons(2,cons(3,nil))) ); /* expect: List[1,2,3] */ print_list(list2= cons(4,cons(5,cons(6,nil))) );
both=append(list,list2); print_list(both); printf("%d",lenght( cons(1,cons(2,cons(3,nil)))) ); return 0; }
it produced an error . after i changed my code the statement.The print_list(both) printed out list[1,2,3,4,5,6,0] i think it was caused by
for (i=0;i<=w;i++){
list3=cons(0,list3); so i changed my code to
for (i=0;i<w;i++){
list3=cons(0,list3); my new code for the append function is
int w= lenght (list)+lenght(list2); int i; Cons* list3; Cons*start1; list3=nil; for (i=0;i<w;i++){
list3=cons(0,list3);
} start1=list3; for (;list!=nil&&list3!=nil;list=list->tail,list3=list3->tail){ list3->head=list->head; } for (;list2!=nil&&list3!=nil;list2=list2->tail,list3=list3->tail){ list3->head=list2->head; } return start1; }