输入一个单向链表,输出该链表中倒数第 k 个结点
2015-08-27 15:33
363 查看
class ListNode { public: ListNode() { pNext = NULL; nValue = 0; } ListNode* pNext; int nValue; }; ListNode* CreaList() { int nValue; ListNode* Head = NULL; ListNode* ListIndex = NULL; while(cin >> nValue) { if (Head == NULL) { Head = new ListNode(); Head->nValue = nValue; ListIndex = Head; } else { ListNode* newNode = new ListNode(); newNode->nValue = nValue; ListIndex->pNext = newNode; ListIndex = newNode; } } // cout << "Print List;" << endl; PrintList(Head); return Head; } void PrintList(ListNode* Head) { for (ListNode* pNode = Head; pNode != NULL; pNode = pNode->pNext) { cout << pNode->nValue << " "; } cout << endl; } //运用两个节点 可以达到通过一次遍历完成输出倒数第K个节点 void PrintTheLastK(ListNode* Head, int K) { if (Head == NULL) { cout << "number of list less then " << K << endl; return; } ListNode* firstPoint = Head; ListNode* secondPoint = Head; for (int i = 1; i < K ; i++) { secondPoint = secondPoint->pNext; if (secondPoint == NULL) { cout << "number of list less then " << K << endl; return; } } while(1) { if (secondPoint->pNext == NULL) { cout << "result:" << firstPoint->nValue << endl; return; } firstPoint = firstPoint->pNext; secondPoint = secondPoint->pNext; } }
//拓展 //输入一个单向链表。如果该链表的结点数为奇数,输出中间的结点;如果链表结点数为偶数,输出中间两个结点前面的一个 void PrintMidNode(ListNode* Head) { if (Head == NULL) { return; } ListNode* firstNode = Head; ListNode* secondNode = Head; while (1) { if (secondNode->pNext == NULL || secondNode->pNext->pNext == NULL) { cout << "result:" << firstNode->nValue << endl; return; } secondNode = secondNode->pNext->pNext; firstNode = firstNode->pNext; } }
相关文章推荐
- 中文版Chrome浏览器不支持12px以下字体的解决方案
- HBase 常用Shell命令
- hdoj3001Travelling【状压dp 类TSP】
- Xamarin莫名奇妙的BUG
- TCP协议缺陷不完全记录
- 使用Category 重写frame
- SolrCloud之分布式索引及与Zookeeper的集成
- [PHP] LAMP环境搭建
- UIPageControl以及滚动视图定时滚动
- JS执行流程
- PPPoE工作原理
- 联合查询问题
- 导航原理实验系统软件——node-webkit初探
- Glibc说明
- ubuntu 软件使用
- 关于C3P0容错和自动重连特性的研究
- unity, 自定义类中使用print
- java.lang.ClassNotFoundException: org.apache.ws.commons.schema.resolver.URIResolver
- 图论:最短路问题 Floyd Dijkstra SPFA算法
- 对深拷贝与浅拷贝的再次理解