您的位置:首页 > 其它

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

2014-06-27 14:31 381 查看
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stack>
using namespace std;

struct Node
{
int data;
struct Node* next;
};

struct Node* create_list(int len)
{
if (len <= 0)
return NULL;

struct Node* head;
struct Node* tmp;
struct Node* pre;
for (int i=0; i<len; i++)
{
if (i == 0)
{
head = tmp = new struct Node;
cin >> tmp->data;
tmp->next = NULL;
pre = tmp;
continue;
}
tmp = new struct Node;
cin >> tmp->data;
tmp->next = NULL;
pre->next = tmp;
pre = tmp;
}

return head;
}

void visit(const struct Node *head)
{
if (head == NULL)
return;
const struct Node *tmp;
tmp = head;
while (tmp)
{
cout << tmp->data;
tmp = tmp->next;
}
}

void free_list(struct Node *head)
{
if (head == NULL)
return;
struct Node *tmp;
while (head)
{
tmp = head;
head = head->next;
delete tmp;
}
}

int main()
{
struct Node *head = create_list(5);
visit(head);
cout << endl;

stack<int> sts;
struct Node* tmp = head;

while (tmp)
{
sts.push(tmp->data);
tmp = tmp->next;
}

while (sts.size() != 0)
{
cout << sts.top();
sts.pop();
}
cout << endl;
free_list(head);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐