C language linked list operation example sharing
- 2020-04-02 02:17:04
- OfStack
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct chaink{
char c;
struct chaink * next;
}ck;
ck * chain(ck *,int);
int print(ck *,int);
int main(void){
printf(" This is a linear linked list test program. n");
ck * head=NULL;
int k;
k=sizeof(ck);
do{
head=chain(head,k);
printf(" Do you want to end the program? If finished, press y/Y ; Press other keys to continue typing. n");
if(getch()=='y' && getch()=='Y'){
printf(" Program ends. n");
getch();
break;
}
}while(1);
return 0;
}
ck * chain(ck * head,int k){
ck * next=NULL;
ck * temp=NULL;
int i=0;
if(head==NULL){
head=(ck*)malloc(k);
if(head==NULL){
printf("malloc Memory error !");
getch();
exit(1);
}
printf(" The header node was successfully created and its address is %p . n",head);
head->next=NULL;
head->c='0';
}
do{
printf(" Do you want to enter new data? If yes, please press y/Y ; Press other keys to finish typing. n");
if(getch()!='y' && getch()!='Y'){
printf(" End of entry. n");
getch();
break;
}
temp=head->next;
head->next=(ck*)malloc(k);
if(head->next==NULL){
printf("malloc Memory error !");
getch();
exit(1);
}
next=head->next;
next->next=temp;
printf(" Please enter new data... n");
next->c=getch();
if(next->c==-1){
printf(" System entry error! ");
getch();
exit(1);
}
printf(" New data entry successful. The new data input is %c , the address of its data node is %p . n",next->c,next);
}while(1);
if(head->next==NULL){
printf(" There is no data in the data chain. n");
getch();
}
else{
printf(" Do you want to display all the data in the linked list and their addresses? To display, press y/Y ; Press the other key to skip. n");
if(getch()!='y' && getch()!='Y'){
printf(" Skip. n");
getch();
return head;
}
printf(" Now output the contents of the linked list... n The serial number data Pointer to the n");
for(next=head->next;next!=NULL;next=next->next){
i=print(next,i);
}
}
return head;
}
int print(ck * next,int i){
printf(" %d %c %pn",i,next->c,next);
i++;
return i;
}