花费了一个下午的时间才成功运行这些代码,因为指针的bug。看来对指针还是需要进一步深入学习。
下面是代码:
困扰的是改成create_list(link_list list, int n)就会有段错误。//main.c#include#include #define OK 0#define ERROR -1typedef struct node{ int data; struct node *next;}NODE, *link_list;/*void create_list(link_list list, int n);int insert_list(link_list list, int index, int elem);int delete_list(link_list list, int index);link_list find_list(link_list list, int index);void print(link_list list);*///新建一个链表,并输入元素link_list create_list( int n){ int i ; link_list p, q; link_list list = (link_list)malloc(sizeof(NODE)); list->next = NULL; q = list; for (i = 1; i <= n; i++) { p = (NODE*)malloc(sizeof(NODE)); printf("enter a data:"); scanf("%d", &p->data); p->next = NULL; q->next = p; //p链接到尾节点 q = p; //q指向尾节点 } return list;}void print(link_list list){ link_list p; p = list->next; for(; p!= NULL; p = p->next) printf("print:%d ", p->data); printf("\n");}//查找指定位置的元素link_list find_list(link_list list, int index){ link_list p; int i = 1; p = list->next; while(p && i < index) { p = p->next; i++; } if (p && i == index) return p; return NULL;}//指定位置插入节点int insert_list(link_list list, int index, int elem){ link_list p, q; if(index == 1) p = list; else p = find_list(list, index-1); if(!p) return ERROR; q = (link_list)malloc(sizeof(NODE)); q->data = elem; q->next = p->next; p->next = q; return OK;}int delete_list(link_list list, int index){ link_list p, q; if (index == 1) p = list; else p = find_list(list, index-1); if (!p) return ERROR; q = p->next; p->next = q->next; free(q); return OK;}int main(){ link_list list = NULL; link_list p; int fb; printf("create list \n"); list = create_list(3); print(list); printf("find\n"); p = find_list(list, 2); printf("find:%d\n", p->data); printf("insert n data\n"); fb = insert_list(list, 2, 2); if (fb == OK) printf("OK\n"); else printf("ERROR\n"); printf("delete \n"); fb = delete_list(list, 2); if (fb == OK) printf("OK\n"); else printf("ERROR\n"); return 0;}