今后实现了一个栈的操作,本来打算用kernel的list,后来发现双指针有点奢侈,所以就自己单链表来实现,代码如下:
----------------------------------------------------------------------------------------
- /*
-
* file: main.c
-
* author: vincent.cws2008@gmail.com
-
* history:
-
* initial @ 2012-02-05
-
*/
-
-
#include <stdio.h>
-
#include "stack.h"
-
-
#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
-
-
void main()
-
{
-
int i;
-
stack_t sk;
-
int array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
-
-
stack_init(&sk);
-
for (i=0; i < ARRAY_SIZE(array); i++)
-
stack_push(&sk, &(array[i]), sizeof(array[i]));
-
-
for (i=0; i < ARRAY_SIZE(array); i++)
-
printf("%d ", *(int*)stack_pop(&sk));
-
-
printf("\n");
-
-
stack_exit(&sk);
-
}
----------------------------------------------------------------------------------------
- /*
-
* file: stack.h
-
* author: vincent.cws2008@gmail.com
-
* history:
-
* initial @ 2012-02-05
-
*/
-
-
-
#ifndef __STACK_H__
-
#define __STACK_H__
-
-
#include <stdlib.h>
-
-
#ifndef __assert
-
#define __assert(x)
-
#endif
-
-
#ifndef NULL
-
#define NULL 0
-
#endif
-
-
extern struct node;
-
extern struct stack;
-
-
typedef struct stack{
-
struct node *head;
-
}stack_t;
-
-
int stack_init(struct stack *sk);
-
int stack_exit(struct stack *sk);
-
-
void *stack_pop(struct stack *sk);
-
void stack_push(struct stack *sk, void *data, size_t size);
-
-
#endif
----------------------------------------------------------------------------------------
- /*
-
* file: stack.c
-
* author: vincent.cws2008@gmail.com
-
* history:
-
* initial @ 2012-02-05
-
*/
-
-
#define DEBUG
-
-
#include "stack.h"
-
#include "stdlib.h"
-
-
#define __malloc(sz) malloc(sz)
-
#define __free(p) free(p)
-
-
-
#define __node_init(pn,pd,sz) {\
-
(pn)->data=(pd); \
-
(pn)->size=(sz); \
-
(pn)->next=NULL; \
-
}
-
-
typedef struct node {
-
void *data;
-
size_t size;
-
struct node *next;
-
} node_t;
-
-
-
void *stack_pop(struct stack *sk)
-
{
-
void *ret=NULL;
-
struct node *mark=NULL;
-
__assert(sk);
-
if (sk->head) {
-
mark = sk->head;
-
ret = mark->data;
-
sk->head = sk->head->next;
-
__free(mark);
-
}
-
return ret;
-
}
-
-
void stack_push(struct stack *sk, void *data, size_t size)
-
{
-
struct node *pnew;
-
__assert(sk && data);
-
pnew = __malloc(sizeof(struct node));
-
__assert(pnew);
-
__node_init(pnew, data, size);
-
/* insert the node to the head of the list */
-
if (sk->head){
-
pnew->next = sk->head;
-
sk->head = pnew;
-
}
-
else {
-
sk->head = pnew;
-
}
-
}
-
-
int stack_init(struct stack *sk)
-
{
-
__assert(sk);
-
sk->head = NULL;
-
return 0;
-
}
-
-
int stack_exit(struct stack *sk)
-
{
-
__assert(sk);
-
while(stack_pop(sk));
-
return 0;
-
}
----------------------------------------------------------------------------------------
代码附件:
stack.rar
阅读(2140) | 评论(0) | 转发(0) |