面试题5: 链表的相关操作
来源:互联网 发布:大数据基金有哪些 编辑:程序博客网 时间:2024/06/05 10:13
1.链表的相关操作,在末尾添加节点,删除指定的节点,逆序输出链表的节点。
源码
/*链表的相关操作*/#include<iostream>#include<stack>#include<stdio.h>using namespace std;struct ListNode{int value;ListNode * pNext;};//add node to the tail of the Listvoid AddToTail(ListNode** pHead, int value){ListNode* pNew = new ListNode();pNew->value = value;pNew->pNext = NULL;if (*pHead == NULL){*pHead = pNew;//cout << (*pHead)->value << endl;}else{ListNode* pNode = *pHead;while (pNode->pNext != NULL){pNode = pNode->pNext;}pNode->pNext = pNew;}}//remove the node void RemoveNode(ListNode** pHead, int value){if (pHead == NULL || *pHead == NULL)return;ListNode* pToBeDeleted = NULL;ListNode* pNode = *pHead;if (pNode->value == value){pToBeDeleted = pNode;pNode = pNode->pNext;}else{while (pNode->pNext != NULL&&pNode->pNext->value != value){pNode = pNode->pNext;}if (pNode->pNext != NULL&&pNode->pNext->value == value){pToBeDeleted = pNode->pNext;pNode->pNext = pNode->pNext->pNext;}if (pToBeDeleted != NULL){delete pToBeDeleted;pToBeDeleted = NULL;}}}//print the node from the headvoid PrintFromHead(ListNode** pHead){int i = 0;ListNode* pNode = *pHead;while (pNode != NULL){cout << "the value of node " << i << ":" << pNode->value << endl;pNode = pNode->pNext;i++;}}//print the node from the tailvoid PrintFromTail(ListNode** pHead){int i = 0;stack<ListNode*>nodes;ListNode* pNode = *pHead;while (pNode != NULL){nodes.push(pNode);pNode = pNode->pNext;}while (!nodes.empty()){pNode = nodes.top();cout << "the value of node " << i << ":" << pNode->value << endl;nodes.pop();i++;}}//printf the node from the tail using recursionvoid PrintFromTailRecursion(ListNode* pHead){//ListNode* pNode = *pHead;int i = 0;if (pHead != NULL){if (pHead->pNext != NULL){PrintFromTailRecursion(pHead->pNext);}cout << "the value of node " << i << ":" << pHead->value << endl;i++;}}//main function int main(){struct ListNode* pHead = NULL;for (int i = 0; i < 10; i++){AddToTail(&pHead, i);}cout << "---Print from the head--- " << endl;PrintFromHead(&pHead);cout << "---After removing digit 5---" << endl;RemoveNode(&pHead, 5);PrintFromHead(&pHead);cout << "---Print from the tail--- " << endl;PrintFromTail(&pHead);cout << "---Print using recursion--- " << endl;PrintFromTailRecursion(pHead);system("PAUSE");return 0;}
0 0
- 面试题5: 链表的相关操作
- 常见的链表相关面试题
- 链表相关的面试题总结
- 链表的相关面试题
- 链表的相关面试题
- 链表相关面试题
- 链表相关面试题
- 链表相关面试题
- 链表相关面试题
- 链表相关面试题
- 链表操作面试题
- 链表操作面试题
- 顺序表和链表的相关热点面试题
- 链表相关的热点面试题(一)
- 链表相关的热点面试题(二)
- 链表相关面试题(zz)
- [各种面试题] 链表相关
- 链表相关面试题(一)
- 更新组合值
- MSQL存储过程
- poj1088滑雪--dp之记忆化搜索
- 框架 day49 BOS项目练习3(修复window控件BUG,添加/修改/作废取派员,datagrid使用,分页查询(DetachedCriteria离线),formatter函数)
- Android "Unable to instantiate fragment"解决方案
- 面试题5: 链表的相关操作
- Android 数据绑定框架DataBinding
- VS2015 密匙
- 数据结构与算法之二 排序
- libsvm python版本在windows7安装错误的解决方法
- Houdini小脚本:提取filecache节点到/out下
- HDU3294 Girls' research
- AsyncTask
- ArcGIS Server中创建的两个账户有什么区别