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

海涛老师的面试题-作业5-从尾到头打印链表

2012-06-26 10:13 369 查看
View Code

// 从尾到头打印链表.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stack>
#include <stdlib.h>
#include <iostream>
using namespace std;

static int arr[5];
struct ListNode
{
int m_nkey;
ListNode* m_pNext;
};

ListNode* NewNode(int key)
{
ListNode* pNode=(ListNode*)malloc(sizeof(struct ListNode));
pNode->m_nkey=key;
pNode->m_pNext=NULL;
return pNode;
}

static void CreateList(ListNode* Head)
{
for(int i=0;i<5;i++)
arr[i]=rand()%100;
for(int i=0;i<5;i++)
cout<<arr[i]<<" ";
cout<<endl;
ListNode* pPrev=Head;
ListNode* pNode;
for(int i=1;i<5;i++)
{
pNode=NewNode(arr[i]);
pPrev->m_pNext=pNode;
pPrev=pNode;
}
}

static void PrintListReversingly_Iter(ListNode* Head) //以栈结构进行反转输出
{
stack<ListNode*> Nodes;
ListNode *pNode=Head;
while(pNode)
{
Nodes.push(pNode);
pNode=pNode->m_pNext;
}
while(!Nodes.empty())
{
pNode=Nodes.top();
cout<<pNode->m_nkey<<"****";
Nodes.pop();
}
}

static void PrintListRecur(ListNode* Head)          //间接以栈结构递归反转输出
{
if(Head)
{
if(Head->m_pNext)
PrintListRecur(Head->m_pNext);
cout<<Head->m_nkey<<"****";
}
}

static void PrintListReverseNode(ListNode* Head)      //修改链表指向来进行反转输出
{
ListNode* pPrev=Head;
ListNode* pNext=NULL;
ListNode* pNode=Head->m_pNext;
Head->m_pNext=NULL;
while(pNode)
{
pNext=pNode->m_pNext;
pNode->m_pNext=pPrev;
pPrev=pNode;
pNode=pNext;
}
while(pPrev)
{
cout<<pPrev->m_nkey<<"****";
pPrev=pPrev->m_pNext;
}
}

int _tmain(int argc, _TCHAR* argv[])
{
ListNode* Head=(ListNode* )malloc(sizeof(struct ListNode));
Head->m_pNext=NULL;
CreateList(Head);
Head->m_nkey=arr[0];
PrintListReversingly_Iter(Head);
cout<<endl;
PrintListRecur(Head);
cout<<endl;
PrintListReverseNode(Head);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: