/* name: list written by: 1jjk */ #include<stdio.h> #include<stdlib.h> /*包含的文件*/
/*声明一个结构体并定义*/ typedef struct node { int data; struct node *next; }*pointer,*klist;
/*声明求表长*/ int lengthlist(klist list);
/*实现建立链表,这里的名写错了,呵呵*/ struct node *insert_list() { klist q,d,list; int x; d=malloc(sizeof(struct node)); list=d; scanf("%d", &x); while(x!=0) { q=malloc(sizeof(struct node)); list->data=x; list->next=q; list=q; scanf("%d", &x); } list->next=NULL; return d; }
/*get the length of the list*/ int lengthlist(klist head) { klist p; int j=0; p=head; printf("\nout is:\n"); while(p->next!=NULL) { printf("%d\n",p->data); p=p->next; j++; } printf("\n"); return j; }
/*search the node of the list*/ struct node *search_list(klist list,int i) { klist p=list; int j=0; while((p->next!=NULL)&&(j<i)) { p=p->next; j++; } if(i==j) { // printf("%d\n",p->data);
return p; } else { return NULL; } }
/*insert one number into a node of the list*/ struct node *into_list(klist list,int num,int i) { klist p,q,d; int j=0; p=list; d=list; if((search_list(list,i))==NULL) { printf("insert error\n"); return d; } while((p->next!=NULL)&&(j<i)) { p=p->next; j++; } if(j==i) { q=malloc(sizeof(struct node)); q->data=num; q->next=p->next; p->next=q; return d; } else { return d; } }
/*delete the number of the list*/ int delete_list(klist list,int i) { klist p,q; int j=0; p=list; if((search_list(list,i))==NULL) { printf("delete error\n"); return 0; } while((p->next!=NULL)&&(j<i)) { p=p->next; j++; } if(j==i) { q=p->next; p->next=q->next; free(q); return 1; } else { return 0; } } int main() { klist p; int i; p=insert_list(); printf("%d\n",lengthlist(p)); printf("please input which node do you want to insert a number:\n"); scanf("%d",&i); search_list(p,i); p=into_list(p,2222,i); lengthlist(p); printf("please input which node do you want to delete:\n"); scanf("%d",&i); delete_list(p,i); return lengthlist(p); }
|