在无头单链表的一个非头节点前插入一个节点
2016-04-29 09:38
429 查看
思路:先遍历找到要插入的结点,然后创造结点,插入
#define _CRT_SECURE_NO_WARNINGS 1 //在无头单链表的一个非头节点前插入一个节点 #include<iostream> using namespace std; #include<iostream> #include<stdlib.h> using namespace std; typedef int DataType; typedef struct SListNode { DataType data; //数据 struct SListNode * next; //指向下一个结点的指针 }SListNode; SListNode* CreateNode(DataType x) //创造结点 { //1.先开辟空间 2.数据赋给data 3.指针置空 SListNode* NewNode = (SListNode*)malloc(sizeof (SListNode)); NewNode->data = x; NewNode->next = NULL; return NewNode; } void PushBack(SListNode * &ppHead, DataType Data) { //1.none 2.one and more if (ppHead == NULL) { ppHead = CreateNode(Data); } else { //1.先找到尾结点 2.把新节点链起来 SListNode* cur = ppHead; while (cur->next) { cur = cur->next; } cur->next = CreateNode(Data); } } //在无头单链表的一个非头节点前插入一个节点 void PushNotHead(SListNode * &ppHead,SListNode* pos, DataType data) { if (ppHead == NULL) //边界条件 return; SListNode* cur = ppHead; while (cur->next!= pos) //找到pos { cur = cur->next; } SListNode* tmp = CreateNode(data); //创造结点 tmp->next = pos; //从后向前链接结点 cur->next = tmp; } //打印 void PrintSNodeList(SListNode *&ppHead) { while (ppHead) { printf("%d->", ppHead->data); ppHead = ppHead->next; } cout << "NULL"; printf("\n"); } void Test() { SListNode* pHead = NULL; PushBack(pHead, 1); PushBack(pHead, 2); PushBack(pHead, 3); PushBack(pHead, 4); PushBack(pHead, 5); PushNotHead(pHead, pHead->next->next, 6); PrintSNodeList(pHead); } int main() { Test(); system("pause"); return 0; }
相关文章推荐
- SURVIVAL SHOOTER TUTORIAL之Player Health & UI & Enemy Attack [6]
- iOS本地数据存取,看这里就够了
- Nginx部署ThinkPHP项目的办法
- log4j.properies详解
- 每天laravel-20160727| Genaerator command-5
- Python松散正则表达式用法分析
- WEB前端性能优化:HTML,CSS,JS和服务器端优化
- string.IsNullOrEmpty和string.IsNullOrWhiteSpace方法的区别
- Mac sublime text3 快捷键
- STL queue队列容器和priority_queue优先队列容器
- mybatis中特殊SQL的几种配置方法
- Android之检查用户是否授予了App所需权限
- ireport 子报表不显示,有数据,但就是在项目中不显示
- 每天laravel-20160727| Genaerator command-5
- spring对乱码的处理及其springmvc核心器注册
- SecureCRT 连接虚拟机Linux
- windows 下 redis for php 配置
- dbda封装类(包括:返回二维数组、Ajax调用返回字符串、Ajax调用返回JSON)
- 分享基于Sails.js和React.js的全栈聊天室
- EasyUI扩展 datagrid列名包含特殊字符会导致表格错位(5)