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

面试题之【从尾到头打印链表】

2014-04-04 10:48 281 查看
关于链表的经典面试题,说实话我第一次看到这个的想法是双向链表,毕竟直接使用链表的话好像这个结构很符合要求了(其实方便的找到前一个元素也是双向链表的设计初衷吧),于是我写出了如下的代码:

#include<iostream>
#include<cstdio>
using namespace std;

class Node
{
public:
int value;
Node* next;
Node* front;
Node()
{
value=0;
next=NULL;
front=NULL;
}
Node(int n):value(n)
{}
};
class linkList
{
public:
Node* head;
Node* tail;
linkList()
{
head=NULL;
tail=NULL;
}
void add(int n)
{
if(head==NULL)
{
head=new Node();
tail=head;
head->value=n;
}
else
{
Node* s=new Node(n);
s->front=tail;
tail->next=s;//shunxu
tail=tail->next;//shunxu
cout<<tail->value<<endl;
cout<<head->next->value<<endl;
}
}
void print()
{
/*Node *p=head;
while(p!=tail->next)
{
printf("%d\n",p->value);
p=p->next;
}*/
Node *q=tail;
while(q!=head->front)
{
printf("%d\n",q->value);
q=q->front;
}
}
};
int main()
{
linkList a;
int n;
while(scanf("%d",&n)==1&&n!=-1)
{
a.add(n);
}
a.print();
return 0;
}


但是后来发现其实这个题目的考点并不是链表,而是栈,因为这就是一个后进先出的结构嘛,但是栈又有显示栈和隐式栈之分,所谓的显示展就是我们把链表中的元素一个个入栈再一个个弹出(也就是直接使用数据结构中的栈),代码如下:

#include<iostream>
#include<cstdio>
const int SIZE=1000000;
class Stack
{
public:
int* a;
int top;
Stack()
{
top=0;
a=new int[SIZE];
}
bool push(int n)
{
if(top>=SIZE)
{
return false;
}
else
{
a[top++]=n;
return true;
}
}
void print()
{
top--;
while(top>=0)
{
printf("%d\n",a[top--]);
}
}
};
int main()
{
int n;
Stack s;
while(scanf("%d",&n)&&n!=-1)
{
if(!s.push(n))
{
return -1;
}
}
s.print();
return 0;
}


而隐式栈则是使用递归的,因为我们知道函数递归调用的过程实际上就是不断压栈的过程,也就是说,通过递归输出链表中的元素也是可以达到这个效果的。但是这个方法有一个缺点就是函数递归调用占用的资源比较多,当递归的层数过深的时候可能会产生栈溢出的现象。代码如下:



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