C语言链表实现。

来源:互联网 发布:淘宝规则最新 编辑:程序博客网 时间:2024/05/16 04:56

主攻C语言教程已经接近尾声,越发激起了学习数据结构的兴趣。学习数据结构不能没有语言功底,要不然各种错误不知如何调试,使用语言也不是十分自然。这两样应该是相得益彰的,学好一种语言,灵活运用,像说话一样,然后掌握技巧。

在数据结构中 链表是非常重要的。下面是对联表的实现以及基本的操作函数。还有一些细节归纳。

typedef char DATA;                         struct linked_list{DATA d;struct linked_list *next;};typedef struct linked_list ELEMENT;typedef ELEMENT *LINK;//递归方式生成链表LINK string_to_list(char s[]){LINK head;if(s[0] == '\0')return NULL;else{head = (LINK)malloc(sizeof(ELEMENT));head->d = s[0];head->next = string_to_list(s + 1);          //s是一个指针通过指针进行移位分别指向字符串的每一个字符。return head;}}//迭代方式生成链表LINK s_to_l(char s[]){LINK head = NULL, tail;int i;if(s[0] != '\0'){head = (LINK)malloc(sizeof(ELEMENT));head->d = s[0];tail = head;for(i = 1; s[i] != '\0'; ++i )// add to tail{tail -> next = (LINK)malloc(sizeof(ELEMENT));tail = tail -> next;tail -> d = s[i];}tail -> next = NULL; }return head;}//对联表进行计数//递归方法int count(LINK head){if(head == NULL)return 0;else{return (1 + count(head -> next));}}//对链表进行计数 迭代方法int count_list(LINK head){int cnt = 0;for(; head != NULL ; head  = head -> next)++cnt;return cnt;}//递归方法输出链表所有元素。void print_list(LINK head){if(head == NULL)printf("NULL");else{printf("%c --> ",head -> d);print_list(head->next);}}///用递归方法连接两个链表void concatenate(LINK a, LINK b){assert( a != NULL);if(a -> next == NULL)a ->next = b;elseconcatenate(a -> next,b);}//递归允许我们在便利量表a时候,避免使用任何辅助指针。一般而言,自引用的字符链表,使递归方法显得十分自然。这些递归形式基本如下/*void generic_recursion(LINK  head){if(head == NULL)do the base oneelsedo the general case and recur with generic_recursion(head -> next);}*/void insert(LINK p1,LINK p2,LINK q){assert( p1 -> next == p2);p1->next = q;q ->next = p2;}int main(void){LINK h;h = string_to_list("ABC");printf("The resulting list is \n");print_list(h);printf("\n This list has %d elements.\n",count(h));return 0;}
有了链表就可以实现堆栈实现队列,(当然用数组也可以,各有各的好处);


1 0
原创粉丝点击