单链表(C语言)基本操作
2016-03-28 20:34
459 查看
单链表:单向有序链表 最后置于空
#pragma once #include<string.h> #include<malloc.h> #include<assert.h> typedef int DataType; typedef struct ListNode { struct ListNode *_next; DataType _data; }ListNode; void PrintList(ListNode *&pHead) { while(pHead) { printf("%d->",pHead->_data); pHead=pHead->_next; } printf("NULL\n"); } ListNode* BuyNode(DataType x) { ListNode *tmp=(ListNode *)malloc(sizeof(ListNode)); tmp->_data=x; tmp->_next=NULL; return tmp; } void PushFront(ListNode *&pHead,DataType x)//首部插入 { if(pHead==NULL) { pHead=BuyNode(x); } else { ListNode *tmp=BuyNode(x); tmp->_next=pHead; pHead=tmp; } } void PopFront(ListNode *&pHead)//首部删除 { if(pHead!=NULL) { ListNode *del=pHead; pHead=del->_next; free(del); } } void PushBack(ListNode *&pHead,DataType x)//尾部插入 { if(pHead==NULL) { pHead=BuyNode(x); } else { ListNode *cur=pHead; while(cur->_next) { cur=cur->_next; } cur->_next=BuyNode(x); } } void PopBack(ListNode *&pHead)//尾部删除 { if(pHead==NULL) { return; } else if(pHead->_next==NULL) { free(pHead); pHead=NULL; } else { ListNode *cur=pHead; ListNode *prev=pHead; while(cur->_next) { prev=cur; cur=cur->_next; } prev->_next=NULL; free(cur); } } ListNode *Find(ListNode *&pHead,DataType x)//查找 { ListNode *cur=pHead; while(cur) { if(cur->_data==x) { return cur; } cur=cur->_next; } return NULL; } void PopNoHead(ListNode *pos)//删除无头单链表的非尾节点 { ListNode *del = pos->_next; assert(pos); pos->_data = del->_data; pos->_next = del->_next; free(del); del=NULL; }//Test.cpp
#include<stdio.h> #include "List.h" void Test1()//输入/出、查找 { ListNode *ret=NULL; ListNode *list=NULL; PushFront(list,1); PushFront(list,2); PushFront(list,3); PushFront(list,4); PushFront(list,5); PrintList(list); Find(list,4); PopFront(list); PopFront(list); PopFront(list); PopFront(list); PrintList(list); }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- 探索PowerShell (二) PowerShell的基本操作
- C#定义并实现单链表实例解析
- C#数据结构之单链表(LinkList)实例详解
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例