算法 链表相邻元素翻转
2015-08-27 08:11
274 查看
链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g。
关键是在于相邻的两个指针的交换过程。
关键是在于相邻的两个指针的交换过程。
#include <iostream> using namespace std; typedef struct _NodeL { int _data; _NodeL *_next; } NodeL; NodeL* swapNode(NodeL* &p, NodeL* pPreLeft) { NodeL* pTmp = NULL; NodeL* pLeft = NULL; NodeL* pRight = NULL; if ((p!= NULL) && (p->_next != NULL)) { pLeft = p; pRight = p->_next; if (pPreLeft!= NULL) { pPreLeft->_next = pRight; } pLeft->_next = pRight->_next; pRight->_next = pLeft; p = pRight; } return pLeft; } void main() { int Test[] = {1,2,3,4,5,6,7,8}; int i = 0; NodeL* Header = NULL; NodeL* pNew = NULL; NodeL* pTail = NULL; for (i=0;i<8;i++) { pNew = new NodeL(); pNew->_data = Test[i]; pNew->_next = NULL; if (i == 0) { Header = pNew; pTail = pNew; } else { pTail->_next = pNew; pTail = pTail->_next; } } pTail = Header; while(pTail!=NULL) { cout << pTail->_data << ", "; pTail = pTail->_next; } pTail = Header; while(pTail!=NULL) { if (pTail == Header) { swapNode(pTail, NULL); Header = pTail; pTail = Header->_next; } else { pTail = swapNode(pTail->_next, pTail); } } cout << endl; pTail = Header; while(pTail!=NULL) { cout << pTail->_data << ", "; pTail = pTail->_next; } cin>>i; }
相关文章推荐
- 程序员和工程师有什么不一样?
- 堆栈的基本特征和基本操作
- fffffffffff
- HDU 3749 Financial Crisis
- WP8.1/Win10/Windows10 PC平台提供密码管理《Enpass》限时免费下载
- 中小站长网站建设发展需注意的的六点ccxtqj
- 我知道点redis-单机数据库(RDB持久化)
- 数据结构的概念和分类
- 展望(开篇)
- 【spoj104】highways
- 用好Python帮助函数help(),dir(),type()
- 使用int?来确保值类型也可以为null
- 第22/24周 等待和I/O延迟统计
- 微软发布《Win10快捷键大全》:Win10桌面版快捷键功能介绍以及官方文档下载
- spring 中的 factory-method 属性
- 《Win10快捷键大全》官方文档下载
- Syntax error, type annotations are available only when source level is at least 1.8
- install ftp client on kail
- 201508025 课后命令练习总结
- rust raw pointer使用方法(3)