Recent Posts

Thứ Hai, 15 tháng 8, 2011

Stack Data Structure ( Linked list)


Implementing a Stack using Link Representation

This is a another version of stack data structure implementation using link representation. With this version the stack size is dynamic and determined at run-time.

linkedstack.h
1int empty(struct node *s);
2struct node* push(struct node *s,int data);
3struct node* pop(struct node *s,int *data);
4void init(struct node* s);
linkedstack.c
01#include<stdlib.h>
02 
03struct node{
04    int data;
05    struct node* next;
06};
07 
08void init(struct node* s){
09    s = NULL;
10}
11 
12struct node* push(struct node* s,int data)
13{
14    struct node* tmp = (struct node*)malloc(sizeof(struct node));
15    if(tmp == NULL){
16        // no memory available
17        exit(0);
18    }
19    tmp->data = data;
20    tmp->next = s;
21    s = tmp;
22    return s;
23}
24struct node* pop(struct node *s,int *element)
25{
26    struct node* tmp = s;
27    *element = s->data;
28    s = s->next;
29    free(tmp);
30    return s;
31}
32 
33int empty(struct node* s){
34    return s == NULL ? 1 : 0;
35}
view source
testlinkedstack.c

Không có nhận xét nào:

Đăng nhận xét