栈作为一种简单但常用的数据结构,要想完全正确的实现还是需要经过一番考虑的。《剑指offer》这本书一再强调代码的鲁棒性。
下面是一个栈的简单c语言实现,作为一个学习过程记录如下。
#include <stdio.h>
#include <stdlib.h>
int gError = 0; //用于栈为空时,仍弹栈的标记
typedef struct Node {
int data;
struct Node* next;
} Node ;
int length(Node*);
void push(Node** stack,const int a)
{
if(*stack==NULL)
{
*stack = (Node*)malloc(sizeof(Node));
(*stack)->data = a;
(*stack)->next = NULL;
} else {
Node* p = *stack;
int len = length(p);
for(int i=0;i<len-1;i++)
{
p = p->next;
}
p->next = (Node*)malloc(sizeof(Node));
p->next->data = a;
p->next->next = NULL;
}
}
int length(Node* head)
{
Node* p = head;
int count = 0;
while(p!=NULL)
{
p = p->next;
count++;
}
return count;
}
int pop(Node** head)
{
if(*head==NULL)
{
fprintf(stdout,"null stack\n");
gError = 1;
return -1;
}
Node* p = *head;
int len = length(p);
int tmp = 0;
Node* prev = NULL;
if(len==1)
{
tmp = p->data;
free(p);
*head = NULL;
} else {
for(int i=0;i<len-1;i++)
{
prev = p;
p = p->next;
}
prev->next = NULL;
tmp = p->data;
free(p);
}
return tmp;
}
void print(Node* head)
{
Node* p = head;
while(p!=NULL)
{
fprintf(stdout,"%3d",p->data);
p = p->next;
}
}
int main(void)
{
Node* head = NULL;
push(&head,13);
push(&head,14);
push(&head,15);
push(&head,16);
print(head);
printf("\n");
printf("top is : %d\n",pop(&head));
printf("top is : %d\n",pop(&head));
printf("top is : %d\n",pop(&head));
printf("top is : %d\n",pop(&head));
return 0;
}