1.C程序内存布局(重点)html
2.malloc()和free()node
3.结构体与指针app
4.链表原理示意图less
5.链表实现(进一步了解能够参考这个博客对链表的实现:http://www.cnblogs.com/wireless-dragon/p/5170565.html)函数
头插法:布局
#include <stdio.h> #include <stdlib.h> typedef struct _st_node { int data; //data area struct _st_node *next; //link next }st_node; void travel_list(st_node *head); int main (int argc, char **argv) { st_node *head = NULL; st_node *new_node; //define new nodes int i; //head insert for(i=0; i<10; i++) { new_node = (st_node *)malloc(sizeof(st_node)); //apply for memory space if(NULL == new_node) { printf("malloc failure\n"); return 0; } new_node->data = i+1; new_node->next = NULL; if(head == NULL) { head = new_node; } else { new_node->next = head; head = new_node; } }
travel_list(head);
return 0; } /*-------End of main()------*/ void travel_list(st_node *head) { st_node *node; node = head; while(node->next != NULL) //最后一个node—>next为空,若是node->next !=NULL,则不会打印1,因此改成node != NULL { printf("data : %d\n", node->data); node = node->next; } return; }
运行结果: 改完后的结果:spa
加入回调函数的代码:3d
#include <stdio.h> #include <stdlib.h> typedef struct _st_node { int data; //data area struct _st_node *next; //link next }st_node; void travel_list(st_node *head, int (*func_ptr) (st_node *node)); int print_data(st_node *node); int print_total(st_node *node);
void destory_list(st_node *head); int main (int argc, char **argv) { st_node *head = NULL; st_node *new_node; //define new nodes int i; //head insert for(i=0; i<10; i++) { new_node = (st_node *)malloc(sizeof(st_node)); //apply for memory space if(NULL == new_node) { printf("malloc failure\n"); return 0; } new_node->data = i+1; new_node->next = NULL; if(head == NULL) { printf("node[%d]\n",new_node->data); head = new_node; } else { printf("node[%d]\n",new_node->data); new_node->next = head; head = new_node; } } travel_list(head, print_data); // travel_list(head, print_total);
destory_list(head);
head = NULL; return 0; } /*-------End of main()------*/ int print_data(st_node *node) { printf("data: %d\n", node->data); } int print_total(st_node *node) { static int total = 0; total += node->data; printf("total: %d\n", total); } void travel_list(st_node *head, int (*func_ptr) (st_node *node)) { st_node *node; node = head; while( node != NULL ) { func_ptr(node); node = node->next; } return; }
//摧毁列表 void destory_list(st_node *head) { st_node *node; do { node = head; head = head->next; printf("free node[%d]\n", node->data); free(node); }while(node != NULL); //用for循环实现 void destory_list(st_node *head) //列表破坏后,head是指向零地址的;那为什还要在破坏后再次使head = NULL?由于函数中的head地址和main中的head { //所在的空间是两个不一样的空间。 st_node *node; for(node=head; node != NULL; node=node->next) { node = head; head = head->next; printf("free node[%d]\n", node->data); free(node); } }
实现指针
运行结果: 摧毁列表:free之后改变。,node仍是指向之前的地址,内容还在,但一旦被别人使用,数据就会改变。code