您的位置:首页 > 其它

单链表逆向打印

2016-05-12 21:40 155 查看
/*输入一个链表的头结点,从尾到头反过来打印出每个结点的值*/

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

递归是最快的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: