面试题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