单链表逆向打印

/*输入一个链表的头结点,从尾到头反过来打印出每个结点的值*/

struct ListNode{
	int m_nKey;
	ListNode* m_pNext;
};

#include "vector"
#include "iostream"

using namespace std;

void printReverseList0(ListNode* head)
{
	vector<int> tmp;
	ListNode *p = head;
	while (p)
	{
		tmp.push_back(p->m_nKey);
		p = p->m_pNext;
	}
	for (int i = static_cast<int>(tmp.size()); i > 0; i--)
	{
		cout << tmp[i-1] << ' ';
	}
	cout << endl;
}

#include "algorithm"
#include "iterator"
void printReverseList01(ListNode* head)
{
	vector<int> tmp;
	ListNode *p = head;
	while (p)
	{
		tmp.push_back(p->m_nKey);
		p = p->m_pNext;
	}
	
	copy(tmp.rbegin(), tmp.rend(),
		ostream_iterator<int>(cout," "));
	cout << endl;
}

#include "stack"
void printReverseList1(ListNode* head)
{
	stack<int> tmp;
	ListNode *p = head;
	while (p)
	{
		tmp.push(p->m_nKey);
		p = p->m_pNext;
	}
	while (!tmp.empty())
	{
		cout << tmp.top() << ' ';
		tmp.pop();
	}
	cout << endl;
}

void printReverseList2(ListNode* head)
{
	if (head)
	{
		printReverseList2(head->m_pNext);
		cout << head->m_nKey << ' ';
	}	
	else
		cout << endl;
}


void freeList(ListNode* head)
{
	ListNode* tmp;
	while (head)
	{
		tmp = head;
		head = tmp->m_pNext;
		delete tmp;
	}
}

#include "time.h"
#include "fstream"
void test()
{
	ListNode *head = NULL;
	ListNode *tail = head;

	for (int i = 0; i < 10; i++)
	{
		ListNode* p = new ListNode;
		p->m_nKey = i;
		p->m_pNext = NULL;
		if (head == NULL)
		{
			head = p;
			tail = p;
		}
		else
		{
			tail->m_pNext = p;
			tail = p;
		}	
	}
	ofstream file;
	file.open("timeResults.txt", ios::app);

	clock_t t0 = clock();
	for (int i = 0; i < 1000; i++)
	{
		printReverseList0(head);
	}
	file << "using vector and print size_t-1~0: " << clock() - t0 << "ms" << endl;
	t0 = clock();
	for (int i = 0; i < 1000; i++)
	{
		printReverseList01(head);
	}
	file << "using vector and ostream_iterator: " << clock() - t0 << "ms" << endl;

	t0 = clock();
	for (int i = 0; i < 1000; i++)
	{
		printReverseList1(head);
	}
	file << "using stack: " << clock() - t0 << "ms" << endl;
	t0 = clock();
	for (int i = 0; i < 1000; i++)
	{
		printReverseList2(head);
	}
	file << "using recursion:" << clock() - t0 << "ms" << endl;
	file << endl;
	file.close();

	freeList(head);
}

int main(void)
{
	test();
	return 0;
}

运行结果(3次):

using vector and print from size_t -1 to 0: 926ms
using vector and ostream_iterator: 806ms
using stack: 798ms
using recursion:751ms

using vector and print from size_t-1 to 0: 956ms
using vector and ostream_iterator: 815ms
using stack: 783ms
using recursion:717ms

using vector and print from size_t-1 to 0: 956ms
using vector and ostream_iterator: 822ms
using stack: 762ms
using recursion:715ms

递归是最快的。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值