xqn2017

导航

【剑指offer】从尾到头翻转打印单链表

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

struct ListNode
{
	int m_Value;
	ListNode *next;
};
void ReversePrint(ListNode* pHead)
{
	std::stack<ListNode*> s;
	ListNode *pTemp = pHead;
	if(NULL == pHead)
	{
		return;
	}
	while(NULL !=pTemp)
	{
		s.push(pTemp);
		pTemp = pTemp->next;
	}
	while(!s.empty())
	{
		pTemp = s.top();
		cout<<pTemp->m_Value;
		s.pop();

	}

}
ListNode *CreateList(int a[],int n)
{
	int i = 0;
	ListNode *pHead = NULL;
	ListNode *pTemp = NULL;
	for(i=0; i <n;i++)
	{
		ListNode *pNew = new ListNode();
		pNew->m_Value = a[i];
		pNew->next = NULL;

		if(pHead == NULL)
		{
			pHead = pNew;
			pTemp = pNew;
		}
		else
		{
			pTemp->next = pNew;
			pTemp = pTemp->next;
		}

	}

	return pHead;
}
int main(void)  
{  
	int a[5] = {1,3,5,7,9};
	ListNode *pHead = CreateList(a,5);
	ReversePrint(pHead);
	return 0;  
}    

  

posted on 2017-12-11 18:19  xqn2017  阅读(234)  评论(0编辑  收藏  举报