C实现单链表
2016-03-24 09:39
447 查看
typedef int DataType; typedef struct ListNode { DataType data; struct ListNode* next; }ListNode; //初始化链表 void InitList(ListNode** pphead) { *pphead = NULL; } //创建节点 ListNode* BuyNode(DataType x) { ListNode* tmp = (ListNode*)malloc(sizeof(ListNode)); assert(tmp); tmp->data = x; tmp->next = NULL; return tmp; } //尾插 void PushBack(ListNode** phead,DataType x) { if(NULL == *phead) { *phead = BuyNode(x); } else { ListNode* tial = *phead; while(tial->next != NULL) { tial = tial->next; } tial->next = BuyNode(x); } } //打印 void Print(ListNode* phead) { ListNode* tmp = phead; while(tmp != NULL) { printf("%d->",tmp->data); tmp = tmp->next; } printf("NULL"); printf("\n"); } //前插 void PushFront(ListNode** phead,DataType x) { if(*phead == NULL) { *phead = BuyNode(x); } else { ListNode* tmp = BuyNode(x); tmp ->next = *phead; *phead = tmp; } } //尾删 void PopBack(ListNode** phead) { if(*phead == NULL) { printf("kd"); return; } else { ListNode* tmp = *phead; (*phead) = (*phead)->next; free(tmp); } } //找节点 ListNode* Find(ListNode* phead,DataType x) { if(NULL == phead) { printf("KONG"); return; } else { ListNode* cur = phead; while(cur) { if(cur->data = x) { return cur; } cur = cur->next; } return cur; } } //插入 void Insert(ListNode* pos,DataType x) { ListNode* tmp = BuyNode(x); tmp->next = pos->next; pos->next = tmp; } //翻转单链表 ListNode* Reverse(ListNode* phead) { ListNode* newhead = NULL; ListNode* tmp = phead; while(tmp) { ListNode* cur = tmp; tmp = tmp->next; cur->next = newhead; newhead = cur; /*ListNode* cur = tmp->next; tmp->next = newhead; newhead = tmp; tmp = tmp->next;*/ } return newhead; } //从尾到头打印单链表 void printListFromTailToHead(ListNode* head) { if(head == NULL) { return; } ListNode *newhead = NULL; ListNode *cur = head; while(cur) { ListNode *tmp = cur; cur = cur->next; tmp->next = newhead; newhead = tmp; } ListNode *p = newhead; while(p) { cout<<p->val<<endl; p = p->next; } }
相关文章推荐
- C# 对List<T>取交集、连集及差集
- jvm的堆,栈,方法区
- 指南针为什么不叫指北针
- NAT
- 用 IntelliJ IDEA 新建 JAVA 工程
- C#解析json字符串总是多出双引号的原因分析及解决办法
- "_iconv", "_iconv_open", "_iconv_close",这种错误的解决办法
- 作业:C++作业2
- JS函数表达式
- 2016.03.24回顾
- 作业:C++作业2
- Java内存模型FAQ(七)同步会干些什么呢
- [置顶] 浅析Linux Device Tree - 基础部分
- [Android] 为Android安装BusyBox —— 完整的bash shell
- TYK配置SSL方案
- ( 转)基于.NET平台常用的框架整理
- 创业须知
- 倒置字符串
- 左滑删除的ListView
- 关于minSdkVersion="8" 升级appcompat_v7包主题"Theme.AppCompat.Light"等不存在的问题