参考了-http://wujie2008.javaeye.com/blog/487015的C下的Stack实现,写了一个Stack实现
#include <stdlib.h> #include <stdio.h>
typedef struct node * Elem;
struct node { int data; Elem next; };
typedef Elem Stack;
void init (Stack stack) { Elem p = (Elem) malloc (sizeof (Elem)); p->next = NULL; stack = p; }
int top (Stack stack) { Elem p = stack->next; if (p != NULL) return p->data; else return NULL; }
int pop (Stack stack) { Elem p = stack->next; if (p != NULL) { int data = p->data; stack->next = p->next; //free (p); 在VS2005下面 释放内存时会发生错误 return data; } else return NULL; }
void push (Stack stack, int data) { Elem p = (Elem) malloc (sizeof (Elem)); p->data = data; p->next =stack->next; stack->next = p; }
void main (int argc, char *argv[]) { //Stack s; 在VS下面必须对s进行初始化,否则会出现错误 Stack s = (Stack) malloc (sizeof (Stack)); init (s); int i; for (i = 0; i < 10; i++) push (s, i); for (i = 0; i < 10 ;i++) printf ("%d\n", pop()); free (s); }
|
阅读(943) | 评论(0) | 转发(0) |