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

面试题5—从尾到头打印链表

2017-06-26 10:17 411 查看
题目:输入一个链表的头结点,从尾到头反过来打印每个节点的值。

代码示例(用栈也行):

#include<iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
class LinkList
{
Node *head;
public:
LinkList();
~LinkList();
bool CreateList(int a[], int n);
bool InsertListF(int data);
void Disp(void);
friend bool InverseList(const LinkList &src, LinkList &dst);

};
LinkList::LinkList()
{
head = new Node();
head->next = NULL;
}
LinkList::~LinkList()
{
Node *p = head->next;
Node *pre = head;
while (p != NULL)
{
delete pre;
pre = p;
p = p->next;
}
delete pre;
}
bool LinkList::CreateList(int a[], int n)
{
if (n <= 0)
return false;
Node *pre = head;
for (int i = 0; i < n; i++)
{
Node *p = new Node();
p->data = a[i];
pre->next = p;
pre = p;
}
pre->next = NULL;
return true;
}
bool LinkList::InsertListF(int data)
{
Node *p = new Node();
p->data = data;
p->next = head->next;
head->next = p;
return true;
}
void LinkList::Disp()
{
Node *p = head->next;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
bool InverseList(const LinkList &src, LinkList &dst)
{
if (src.head->next == NULL)
return false;
Node *p = src.head->next;
while (p != NULL)
{
int temp = p->data;
dst.InsertListF(temp);
p = p->next;
}
}

void main()
{
LinkList L1, L2;
int a[4] = { 1,2,4,5 };
//源链表
L1.CreateList(a, 4);
L1.Disp();
//源链表反向输出
InverseList(L1, L2);
L2.Disp();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: