0% found this document useful (0 votes)
8 views3 pages

Ds 8

The document contains a C program that implements a stack using a linked list. It includes functions for creating nodes, inserting and deleting nodes from the stack, checking if the stack is empty, pushing and popping elements, peeking at the top element, and printing the stack. The main function demonstrates the usage of these stack operations.

Uploaded by

ankurkumar99421
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

Ds 8

The document contains a C program that implements a stack using a linked list. It includes functions for creating nodes, inserting and deleting nodes from the stack, checking if the stack is empty, pushing and popping elements, peeking at the top element, and printing the stack. The main function demonstrates the usage of these stack operations.

Uploaded by

ankurkumar99421
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <stdio.

h>
#include <malloc.h>
typedef struct Node {
int data;
struct Node* next;
} node;
node* createNode(int data)
{
node* newNode = (node*)malloc(sizeof(node));
if (newNode == NULL)
return NULL;
newNode->data = data;
newNode->next = NULL;
return newNode;
}
int insertBeforeHead(node** head, int data)
{
node* newNode = createNode(data);
/
if (!newNode)
return -1;
if (*head == NULL) {
*head = newNode;
return 0;
}
newNode->next = *head;
*head = newNode;
return 0;
}
int deleteHead(node** head)
{
node* temp = *head;
*head = (*head)->next;
free(temp);
return 0;
}
int isEmpty(node** stack) { return *stack == NULL; }
void push(node** stack, int data)
{
if (insertBeforeHead(stack, data)) {
printf("Stack Overflow!\n");
}
}
int pop(node** stack)
{
if (isEmpty(stack)) {
printf("Stack Underflow\n");
return -1;
}
deleteHead(stack);
}
int peek(node** stack)
{
if (!isEmpty(stack))
return (*stack)->data;
else
return -1;
}
void printStack(node** stack)
{
node* temp = *stack;
while (temp != NULL) {
printf("%d-> ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main()
{
node* stack = NULL;
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
push(&stack, 40);
push(&stack, 50);
printf("Stack: ");
printStack(&stack);
pop(&stack);
pop(&stack);
printf("\nStack: ");
printStack(&stack);
return 0;

You might also like