查找单链表的中间节点,要求只能遍历一次链表
2016-04-30 16:15
761 查看
思路:快慢指针
//查找单链表的中间节点,要求只能遍历一次链表 #include<iostream> using namespace std; #include<assert.h> 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 PrintSNodeList(SListNode *&ppHead) { while (ppHead ) { printf( "%d->", ppHead ->data); ppHead = ppHead ->next; } cout << "NULL" << endl; } //查找单链表的中间节点,要求只能遍历一次链表 //快慢指针 SListNode* FindMidOneTime(SListNode * pHead) { assert(pHead != NULL); SListNode* fast = pHead ; SListNode* slow = pHead ; while (fast) { if (fast->next) { fast = fast->next->next; } else { break; } slow = slow->next; } return slow; } void Test() { SListNode* pHead = NULL ; PushBack(pHead, 1); PushBack(pHead, 2); PushBack(pHead, 3); PushBack(pHead, 4); PushBack(pHead, 5); PushBack(pHead, 6); PushBack(pHead, 7); cout << FindMidOneTime(pHead)->data<< endl; } int main() { Test(); system( "pause"); return 0; }
相关文章推荐
- Spring——AOP
- Spring——基于注解方式的依赖注入
- 1023. 组个最小数 (20)
- 手机端多线程下载
- IntelliJ IDEA2016.1 + maven 创建java web 项目
- 多媒体编程的实战
- How to submit a package to PyPI
- java之Integer类的一些用法
- Spring——基于XML配置的依赖注入
- 简单分析蔡英文上台对两岸关系的影响
- leetcode 054 Spiral Matrix
- hdu_2717_Catch That Cow_bfs
- Unicode 字符集、编码 相关的基本介绍
- Mysql中导入和导出数据库
- hdu_2717_Catch That Cow_bfs
- SQL Server安全(11/11):审核(Auditing)
- Codeforces Round #349 (Div. 2) C. Reberland Linguistics DP+set
- 深度解析消毒的应用
- CentOS 6,7系统服务管理
- HDOJ(HDU) 2103 Family planning(需要注意范围)