您的位置:首页 > 职场人生

面试题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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: