This is a simple program to do a Stack operation by linked lists this is the formal way .I understand the concept of pointers needed to indicate the top of stack and the pointer to point to the next node.But is it necessary to make pointer variables of the Structure Variable in this case struct student variable i.e typedef to Student .I declared as Student *(any name);.and then dynamically allocate memory through malloc.I could instead use a global variable as Student (anyname);and use is to fill information then push to stack.So what is the difference and advantages and disadvantages to use global variables or pointers.
And about the program i myself wrote it and it is working fine.
typedef struct student{
int roll;
char name[30];
struct student *next;
}Student;
typedef struct stack{
Student *top;
}Stack;
Student *makestudent(int r,char n[]){
Student *newstudent;
if((newstudent=(Student *)malloc(sizeof(Student)))==NULL){
printf("Out Of Memory");
}
else{
newstudent->roll=r;
strcpy(newstudent->name,n);
newstudent->next=NULL;
}
return newstudent;
}
void push(int r,char n[],Stack *s){
Student *student=makestudent(r,n);
student->next=s->top;
s->top=student;
}
Student *pop(Stack *s){
Student *st=s->top;
s->top=s->top->next;
return st;
}
Here is some code using a static array LIFO stack, without using pointers. The major problem is you have to guess how big this stack will be. If you want to reallocate when it grows too big, you are back to using pointers.
#include <stdio.h>
#include <string.h>
#define MAXS 10 // stack size
typedef struct {
int roll;
char name[30];
} student;
student studs [MAXS];
int stacktop = 0;
int push(student *s) {
if (stacktop >= MAXS)
return 1; //mega fail
studs [stacktop++] = *s;
return 0;
}
int pop(student *s) {
if (stacktop <= 0)
return 1; //mega fail
*s = studs [--stacktop];
return 0;
}
int main(void) {
student entryput = {42, "Arthur Dent"};
student entryget;
if (push (&entryput))
return 1; // need to handle better than this
if (pop (&entryget))
return 1; // need to handle better than this
printf ("Name: %s, Roll: %d\n", entryget.name, entryget.roll);
return 0;
}
Program output:
Name: Arthur Dent, Roll: 42