Implementing Stacks, Queues, and Linked Lists in C
Posted on Apr 3, 2026 in Computers
Stack Implementation
typedef struct Node {
int value;
struct Node* next;
} *pNode;
typedef struct Stack {
pNode top;
int len;
} *pStack;
pStack createStack() {
pStack pS = (pStack)malloc(sizeof(struct Stack));
if (pS) {
pS->top = NULL;
pS->len = 0;
}
return pS;
}
int isEmpty(pStack pS) {
if (pS->top && pS->len) return 0;
return 1;
}
int push(pStack pS, int c) {
pNode p = (pNode)malloc(sizeof(struct Node));
if (p) {
p->value = c;
p->next = pS->top;
pS->top = p;
pS->len++;
return 1;
}
return 0;
}
int pop(pStack pS) {
pNode p = pS->top;
int c = p->value;
pS->top = p->next;
free(p);
pS->len--;
return c;
}
void showStack(pStack pS) {
pStack qS = createStack();
int c;
if (isEmpty(pS)) printf("Stack is empty\n");
else {
while (!isEmpty(pS)) {
c = pop(pS);
printf("%d ", c);
push(qS, c);
}
printf("\n");
while (!isEmpty(qS)) {
c = pop(qS);
push(pS, c);
}
}
free(qS);
}
void clearStack(pStack pS) {
while (!isEmpty(pS)) {
pop(pS);
}
}
Queue Implementation
typedef struct Node {
int value;
struct Node* next;
} *pNode;
typedef struct Queue {
pNode beg, end;
int len;
} *pQueue;
pQueue createQueue() {
pQueue pQ = (pQueue)malloc(sizeof(struct Queue));
pQ->beg = NULL;
pQ->end = NULL;
pQ->len = 0;
return pQ;
}
int isEmpty(pQueue pQ) {
if (pQ->len > 0) return 0;
return 1;
}
void put(pQueue pQ, int value) {
pNode p = (pNode)malloc(sizeof(struct Node));
p->value = value;
p->next = NULL;
if (pQ->end != NULL) pQ->end->next = p;
else pQ->beg = p;
pQ->end = p;
pQ->len++;
}
int take(pQueue pQ) {
pNode p = pQ->beg;
int value = p->value;
pQ->beg = p->next;
free(p);
pQ->len--;
return value;
}
void showQ(pQueue pQ) {
if (isEmpty(pQ)) {
puts("Queue is empty");
} else {
pNode current = pQ->beg;
while (current != NULL) {
printf("%d ", current->value);
current = current->next;
}
printf("\n");
}
}
Linked List Implementation
typedef struct Node {
int value;
struct Node* next;
} *pNode;
typedef struct List {
pNode top;
int len;
} *pList;
pList createList() {
pList New = (pList)malloc(sizeof(struct List));
if (New) {
New->top = NULL;
New->len = 0;
}
return New;
}
int isEmpty(pList pL) {
if (pL->top && pL->len) return 0;
return 1;
}
void showList(pList pL) {
if (isEmpty(pL)) printf("List is empty\n");
pNode p = pL->top;
while (p) {
printf("%d ", p->value);
p = p->next;
}
}
pNode findNode(pList pL, int c) {
pNode p = pL->top;
if (isEmpty(pL)) return NULL;
while (p && p->value != c) p = p->next;
return p;
}
int delNode(pList pL, pNode pN) {
pNode p = pN->next;
if (pL->len == 1) {
free(pL->top);
pL->top = NULL;
pL->len--;
return 1;
}
if (p) {
pN->next = p->next;
free(p);
pL->len--;
return 1;
}
return 0;
}