C语言链表的简单实用
// // ViewController.m // 链表 // // Created by 张凯泽 on 16/1/26. // Copyright © 2016年 rytong_zkz. All rights reserved. // #import "ViewController.h" /* static 关键字的作用: (1)函数体内 static 变量的作用范围为该函数体,不同于 auto 变量,该变量的内存只被分配一次, 因此其值在下次调用时仍维持上次的值; (2)在模块内的 static 全局变量可以被模块内所用函数访问,但不能被模块外其它函数访问; (3)在模块内的 static 函数只可被这一模块内的其它函数调用,这个函数的使用范围被限制在声明 它的模块内; (4)在类中的 static 成员变量属于整个类所拥有,对类的所有对象只有一份拷贝; (5)在类中的 static 成员函数属于整个类所拥有,这个函数不接收 this 指针,因而只能访问类的static 成员变量。 */ typedef struct list{ int num; struct list * next; }List; @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // int a =[self lianbiao]; // printf(@"______________%d",a); } -(void)stransition:(int**)p { printf("p = %p\n",p); } -(int)lianbiao { List * head = NULL; //int i = 0; head = initList(); printf("head = %p",head); if (head == NULL) { return -1; } insertList(&head ,2); insertList(&head ,4); insertList(&head ,6); insertList(&head ,3); insertList(&head ,1); priList(head); deleteList(&head ,1); priList(head); deleteList(&head ,2); priList(head); deleteList(&head ,3); priList(head); freeList(&head); return 0; } //初始化链表 static List * initList() { List * list = NULL; list = (List*)malloc(sizeof(List)); if (list == NULL) { return NULL; } list ->next = NULL; return list; } //打印链表信息 static void priList(List* list) { if (list == NULL) { return; printf("------------\n"); } while (list ->next) { printf("%d\n",list -> next ->num); list = list -> next; } printf("-----------\n"); return; } //根据num大小插入链表节点 static int insertList(List** list , int num) { List * now = NULL; List * head = *list;//这里*list的地址就是 刚开始初始化获得地址head的地址 now = initList(); if (now == NULL) { return -1; } now -> num = num; while (head ->next && num >= head -> next -> num) { head = head ->next; } if (head -> next == NULL) { head -> next = now; }else{ now -> next = head -> next; head -> next = now; } return 0; } //计算链表的长度 static int numList (List * head) { int len = 0; while (head && head -> next) { len ++ ; head = head -> next; } return len; } //调用free 逐个释放链表的节点 static void freeList(List** list) { List* head = *list; List* p = NULL; while (head) { p = head; head = head ->next; free(p); } printf("free List ok \n"); return; } //删除对应位置的节点 static int deleteList(List** list , int location) { List * head = *list; List* p = NULL; int i = 1; if (location <= 0 || location > numList(head)) { return -1; } while (i++ <location && head -> next) { head = head -> next; } p = head -> next; head -> next = p -> next; if (p) { free(p); p = NULL; } return 0; } @end