面试题5: 链表的相关操作
2016-06-08 19:13
375 查看
1.链表的相关操作,在末尾添加节点,删除指定的节点,逆序输出链表的节点。
源码
源码
/*链表的相关操作*/ #include<iostream> #include<stack> #include<stdio.h> using namespace std; struct ListNode { int value; ListNode * pNext; }; //add node to the tail of the List void 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 head void 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 tail void 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 recursion void 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; }
相关文章推荐
- Web前端面试题目及答案汇总
- ZooKeeper程序员指南(转)
- 一道面试题,想明白之后好像锤自己几下~~
- Hadoop工程师面试题解析
- Android 面试题总结之Android 进阶(一)
- 程序员福利:各大平台免费接口
- [转]一道题识别优秀的程序员
- 淘宝网前端开发面试题(二)--JS 面试题
- google面试题
- 有哪些野路子电脑技能让非程序员感到神奇?
- 十二个程序员必备的优质资源推荐
- 面试(2)-java-se-HashSet和TreeSet
- 奋斗吧,程序员——第五十三章 万里赴戎机,关山度若飞
- google面试题:判断是否是2的偶数次幂
- Android 面试题总结之Android 进阶(一)
- google 面试题
- 最近的面试小结
- 面试题92:两个链表集合做差
- 《程序员修炼之道--从小工到专家》阅读笔记01
- 程序员实习电话面试