スタックの作成
連結リスト勉強の続きでスタックの作成を挑戦してみました。
createstack.c
#include <stdio.h>
#include <stdlib.h>
//node declaration
struct node{
int data;
struct node *link;
};
//function declaration
void push(struct node **, int);
int pop(struct node **);
int count(struct node *);
void stack_display(struct node *);
void main(){
//declare pointer to point to top of stack
struct node *top;
//declare variable to store data of node in stack
int item;
//point to empty stack
top = NULL;
//push node to stack
push(&top,11);
push(&top,12);
push(&top,13);
push(&top,14);
push(&top,15);
push(&top,16);
push(&top,17);
printf("Items in stack\n");
//display stack
stack_display(top);
//count number of node in stack
printf("No. of items in stack = %d\n",count(top));
printf("Items extracted from stack:\n");
//extract node from beginning of stack
item = pop(&top);
//display data in node
printf("%d\n",item);
//extract node from beginning of stack
item = pop(&top);
//display data in node
printf("%d\n",item);
//extract node from beginning of stack
item = pop(&top);
//display data in node
printf("%d\n",item);
printf("Items in stack\n");
//display stack
stack_display(top);
//count number of node in stack
printf("No. of items in stack = %d\n",count(top));
}
//append new node at the beginning of stack
void push(struct node **q, int num){
struct node *r;
//create new node
r = malloc(sizeof(struct node));
//set data of new node
r->data = num;
//set link of new node to point to first node pointed by top
r->link = *q;
//set p to point to new node
*q = r;
}
//remove node from the beginning of stack
int pop(struct node **q){
int num;
struct node *temp;
//initialize locator pointer
temp = *q;
//if stack is empty
if(temp==NULL){
printf("The stack is empty.\n");
return;
}else{
//point p to next node
*q = temp->link;
//get data in node
num = temp->data;
//delete node
free(temp);
}
return num;
}
//count number of nodes in stack
int count(struct node *q){
int c=0;
while(q!=NULL){
c++;
//go to next node
q = q->link;
}
return c;
}
//display nodes in stack
void stack_display(struct node *q){
while(q!=NULL){
printf("%d\n",q->data);
//go to next node
q = q->link;
}
}