链表(list)的实现(c语言)
2016-03-12 15:52
288 查看
链表是一种基本的数据结构,今天练习了一下,所以将代码贴在下面,代码测试通过,代码还可以优化,我会过段时间就会增加一部分或者优化一部分直达代码无法优化为止,我的所有数据结构和算法都会用这样的方式在博客上面更新。
#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; }
相关文章推荐
- C++ Primer 5th - 1.1 编写一个简单的C++程序
- C/C++基础知识(一)数组和指针
- (各个公司面试原题)在线做了一套CC++综合測试题,也来測一下你的水平吧(二)
- C++第1-1次上机实验
- C语言中a=b=c,a=b==c,a==(b=c),a==(b==c)的简单分析
- 详解C++循环创建多级目录及判断目录是否存在的方法
- C++第一次实验—2
- C++ auto类型说明符
- C++ auto类型说明符
- C++ 单例模式实现代码
- C++开源库
- C++第一次上机报告 1-2
- C++11 lambda表达式
- c++第2次上机实验-1
- Thinking in c++ exercise 4-26 关于二维数组指针
- VC++ Excel电子表格读写示例
- c++ 实现动态顺序表(拷贝构造 赋值运算符重载等操作)
- c++ 写时拷贝
- c++ 深浅拷贝(传统写法 xain'dai'xie'fa)
- c语言常见50题 及答案(递归 循环 以及常见题目)