看欧立奇的《程序员面试宝典》的栈和队列的部分,发现了部分问题。
其中栈的部分,不能简单的用malloc函数来初始化Stack,应该调用create()函数;而且栈的base应该指向栈的最下面的数据的下一个地址。全部调试通过
栈的部分通过单链表来实现链栈的结构:
#include <iostream>
using namespace std;
#define LEN sizeof(Node)
typedef struct student
{
int data;
struct student *next;
}Node;
typedef struct stack
{
Node *base;
Node *top;
}Stack;
Stack *create()
{
Stack *s;
s=(Stack *)malloc(sizeof(Stack));
s->base = s->top =(Node*)malloc(LEN);
s->base->next = NULL;
s->top->next = NULL;
return s;
}
Stack *push(Stack *s,int e)
{
Node *s_new;
s_new = (Node*)malloc(LEN);
s_new->data = e;
s_new->next =NULL;
if(s->top == s->base)
{
s->top = s_new;
s_new->next = s->base;
}
else
{
s_new->next =s->top;
s->top = s_new;
}
return s;
}
Stack *pop(Stack *s)
{
Node *s_pop;
s_pop = s->top;
if(s->top == s->base)
{
cout<<"The stack is empty"<<endl;
}
else
{
if(s_pop->next == s->base)
{
s->top->next = NULL;
s->base->next = NULL;
free(s_pop);
}
else
{
s->top = s->top->next;
free(s_pop);
}
}
return s;
}
void print(Stack *s)
{
Node *p =s->top;
while(p != s->base)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
void main()
{
Stack *s;
s = create();
s = push(s,12);
print(s);
s = push(s,14);
print(s);
s = pop(s);
print(s);
}
欧立奇的《程序员面试宝典》,其中队列部分,存在问题:队列的创建不能简单的使用malloc函数,而应该调用函数create();队列的front应该指向队列最前方的数据的前一个地址
#include <iostream>
using namespace std;
typedef struct student
{
int data;
struct student *next;
}Node;
typedef struct Quene
{
Node *front; //队列头
Node *rear; //队列尾
};
Quene *create( )
{
Quene *Q;
Q = (Quene *)malloc(sizeof(Quene));
Q->front = Q->rear =(Node *)malloc(sizeof(Node));
Q->front->next = Q->rear->next = NULL;
return Q;
}
//在队列尾部添加数据
Quene *insert(Quene *Q,int e)
{
Node *q_new;
q_new =(Node*)malloc(sizeof(Node));
q_new->data =e;
q_new->next =NULL;
if (Q->rear == Q->front)
{
Q->rear = q_new;
Q->front->next = q_new;
}
else
{
Q->rear->next = q_new;
Q->rear =q_new;
}
return Q;
}
Quene *del(Quene *Q)
{
Node *p;
if(Q->front == Q->rear)
{
cout<<"the quene is empty";
}
else
{
p=Q->front->next;
if(p == Q->rear)
{
free(p);
Q->front = Q->rear;
Q->front->next = NULL;
Q->rear->next = NULL;
}
else
{
Q->front->next = Q->front->next->next;
free(p);
}
}
return Q;
}
void print(Quene *Q)
{
Node *p;
p = Q->front->next;
while(p != NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
void main()
{
Quene *Q,*Q_new;
Q=create();
Q_new=insert(Q,23);
print(Q);
Q_new=insert(Q_new,12);
print(Q_new);
Q_new=del(Q_new);
print(Q);
}