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

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

 1 #include<iostream>
 2 #include<cstdio>
 3 using namespace std;
 4 
 5 class Node
 6 {
 7     public:
 8     int value;
 9     Node* next;
10     Node* front;
11     Node()
12     {
13         value=0;
14         next=NULL;
15         front=NULL;
16     }
17     Node(int n):value(n)
18     {}
19 };
20 class linkList
21 {
22     public:
23     Node* head;
24     Node* tail;
25     linkList()
26     {
27         head=NULL;
28         tail=NULL;
29     }
30     void add(int n)
31     {
32         if(head==NULL)
33         {
34             head=new Node();
35             tail=head;
36             head->value=n;
37         }
38         else
39         {
40             Node* s=new Node(n);
41             s->front=tail;
42             tail->next=s;//shunxu
43             tail=tail->next;//shunxu
44             cout<<tail->value<<endl;
45             cout<<head->next->value<<endl;
46         }
47     }
48     void print()
49     {
50         /*Node *p=head;
51         while(p!=tail->next)
52         {
53             printf("%d\n",p->value);
54             p=p->next;
55         }*/
56         Node *q=tail;
57         while(q!=head->front)
58         {
59             printf("%d\n",q->value);
60             q=q->front;
61         }
62     }
63 };
64 int main()
65 {
66     linkList a;
67     int n;
68     while(scanf("%d",&n)==1&&n!=-1)
69     {
70         a.add(n);
71     }
72     a.print();
73     return 0;
74 }

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

 1 #include<iostream>
 2 #include<cstdio>
 3 const int SIZE=1000000;
 4 class Stack
 5 {
 6     public:
 7     int* a;
 8     int top;
 9     Stack()
10     {
11         top=0;
12         a=new int[SIZE];
13     }
14     bool push(int n)
15     {
16         if(top>=SIZE)
17         {
18             return false;
19         }
20         else
21         {
22             a[top++]=n;
23             return true;
24         }
25     }
26     void print()
27     {
28         top--;
29         while(top>=0)
30         {
31             printf("%d\n",a[top--]);
32         }
33     }
34 };
35 int main()
36 {
37     int n;
38     Stack s;
39     while(scanf("%d",&n)&&n!=-1)
40     {
41         if(!s.push(n))
42         {
43             return -1;
44         }
45     }
46     s.print();
47     return 0;
48 }

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

image

posted @ 2014-04-04 10:48  mrbean  阅读(364)  评论(0编辑  收藏  举报