链表(list)的实现(c语言)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表(list)的实现(c语言)相关的知识,希望对你有一定的参考价值。
链表是一种基本的数据结构,今天练习了一下,所以将代码贴在下面,代码测试通过,代码还可以优化,我会过段时间就会增加一部分或者优化一部分直达代码无法优化为止,我的所有数据结构和算法都会用这样的方式在博客上面更新。
#include <stdio.h> #include <stdlib.h> struct node { int key; struct node *next; }; typedef struct node Node; Node *head = NULL; void insert(int num) { Node * new_node, *current; new_node = (Node*)malloc(sizeof(Node)); new_node->key = num; if(head == NULL || head->key > num) { new_node->next = head; head = new_node; } else { current = head; while(1) { if(current->next ==NULL || current->next->key > num ) { new_node->next = current->next; current->next = new_node; break; } else { current = current->next; } } } } void print() { Node * current; if(head == NULL) { printf("链表为空!\n"); } current = head; while(current != NULL) { printf("%d\n",current->key); current = current->next; } } Node * delete(int num) { Node * current = head; Node * answer; if(head != NULL && head->key == num) { head = head->next; return current; } else if(head != NULL && head->key > num) { return NULL; } while(current != NULL) { Node * answer; if(current->next != NULL && current->next->key == num) { answer = current->next; current->next = current->next->next; return answer; }else if(current->next != NULL && current->next->key > num) { return NULL; } current = current->next; } return NULL; } int main() { Node * x; insert(14); insert(2); insert(545); insert(44); print(); x = delete(44); if(x != NULL) { free(x); } print(); return 0; }
以上是关于链表(list)的实现(c语言)的主要内容,如果未能解决你的问题,请参考以下文章