0% found this document useful (0 votes)
148 views

Strings and Stack Operations (Arrays and Dynamic Memory)

This document discusses strings in C programming. It defines strings as arrays of characters terminated with a null character. It describes how to declare, initialize, read, and manipulate strings. Functions like strlen(), strcpy(), strcmp() are introduced to get the length, copy, and compare strings. The document also discusses passing strings to functions and storing strings in a two-dimensional character array to represent an array of strings.

Uploaded by

BALAJI BV
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
148 views

Strings and Stack Operations (Arrays and Dynamic Memory)

This document discusses strings in C programming. It defines strings as arrays of characters terminated with a null character. It describes how to declare, initialize, read, and manipulate strings. Functions like strlen(), strcpy(), strcmp() are introduced to get the length, copy, and compare strings. The document also discusses passing strings to functions and storing strings in a two-dimensional character array to represent an array of strings.

Uploaded by

BALAJI BV
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Data Structures and Applications (BCS304) Module 2: Stacks and Queues

1.5 Strings
 A String is a sequence of characters terminated with a null character ‘\0’.
 The C String is stored as an array of characters.
 The difference between a character array and a C string is that the string in C is terminated
with a unique character ‘\0’.
 To use string functions in c we should use <string.h> header file.

Syntax
 Declaring a string in C is as simple as declaring a one-dimensional array. Below is the basic
syntax for declaring a string.
char string_name[size];
 In the above syntax string_name is any name given to the string variable and size is used
to define the length of the string, i.e the number of characters strings will store.
 There is an extra terminating character which is the Null character (‘\0’) used to indicate
the termination of a string that differs strings from normal character arrays.

Initialization
 A string in C can be initialized in 4 different ways.

1. Assigning a String Literal without Size


 String literals can be assigned without size.
 Here, the name of the string str acts as a pointer because it is an array.
char str[] = "DataStructure";

2. Assigning a String Literal with a Predefined Size

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 1 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

 String literals can be assigned with a predefined size.


 But we should always account for one extra space which will be assigned to the null
character.
 If we want to store a string of size n then we should always declare a string with a size
equal to or greater than n+1.
char str[50] = "DataStructure";

3. Assigning Character by Character with Size


 We can also assign a string character by character. But we should remember to set the end
character as ‘\0’ which is a null character.
char str[14] = { 'D','a','t','a','S','t','r','u','c','t','u','r','e','\0'};

4. Assigning Character by Character without Size


 We can assign character by character without size with the NULL character at the end. The
size of the string is determined by the compiler automatically.
char str[] = { 'D','a','t','a','S','t','r','u','c','t','u','r','e','\0'};

C Program to find length of the String


#include <stdio.h>
#include <string.h>
int main() {
char str[] = "DataStructures"; // declare and initialize string
printf("%s\n", str); // print string
int length = 0;
length = strlen(str);
printf("Length of string str is %d", length); // displaying the length of string
return 0;
}
Output: DataStructures Length of string str is 14

C Program to read a String Input from the User


#include<stdio.h>

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 2 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

int main() {
char str[50];
printf("Enter the String:”);
scanf("%s",str); // reading string
printf("%s",str); // print string
return 0;
}
Output: Enter the String: Data Structures Data
Enter the String: DataStructures DataStructures

Note: Here, the string is read only till the whitespace is encountered.

 To Read a String Separated by Whitespaces


scanf("%[^\n]s", str); printf("%s", str);
gets(str); puts(str);

Passing Strings to Function


 As strings are character arrays, we can pass strings to functions in the same way we pass
an array to a function. Below is a sample program to do this:
// C program to illustrate how to pass string to functions
#include <stdio.h>
void display(char str[]) {
printf("String is : %s", str);
}
int main() {
char str[] = "DataStructures"; // declare and initialize string
display(str); // print string by passing string to a function
return 0;
}
Output: String is : DataStructures

Strings and Pointers in C


 In Arrays, the variable name points to the address of the first element.

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 3 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

 Below is the memory representation of the string str = “DataStructures”.


 Program
#include <stdio.h>
int main() {
char str[20] = "Data Structures";
char* ptr = str; //pointer variable to char array
while (*ptr != '\0') //loop untill NULL character is encountered
{
printf("%c", *ptr);
ptr++;
}
return 0;
}
Output: Data Structures

Array of Strings in C
 In C programming String is a 1-D array of characters and is defined as an array of
characters.
 But an array of strings in C is a two-dimensional array of character types. Each String is
terminated with a null character (\0). It is an application of a 2d array.
 Syntax
char variable_name[r] = {list of string};
var_name is the name of the variable in C.
r is the maximum number of string values that can be stored in a string array.
c is the maximum number of character values that can be stored in each string array.
 Example
#include <stdio.h>
int main()
{
// Declare an array of strings
char names[10][20];
int n;

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 4 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

printf("Enter no. of names to read:", n);


scanf("%d",&n);
// Read names from the user
for (int i = 0; i < n; i++)
{
printf("Enter name %d: ", i + 1);
scanf("%s", names[i]);
}

// Display each string in the array


for (int i = 0; i < n; i++) {
printf("Name %d: %s\n", i + 1, names[i]);
}
return 0;
}

1.5.1 String Functions


String Function Definition Syntax

strcat() It will append a copy of the char *strcat(char* dest, const char
String source string to the end of the *src);
Concatenation destination string. dest: Destination string
src: Source string
returns a pointer to the dest string.
strncat() Function appends not more char* strncat(char* dest, const char*
String Concatenation than n characters from the src, size_t n);
with number of string pointed to by src to the where n represents the maximum
characters to append end of the string pointed by number of characters to be appended
dest plus a terminating Null- size_t is a special unsigned integer
character.

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 5 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

strlen() Calculates the length of a int strlen(const char *str);


String length given string. It doesn’t count
the null character ‘\0’.
strcmp() Function takes two strings as int strcmp(const char *str1, const
String Compare arguments and compares these char *str2);
two strings lexicographically str1: This is the first string to be
compared.
str2: This is the second string to be
compared.
Return Value
 If str1 is less than str2, the return
value is less than 0.
 If str1 is greater than str2, the return
value is greater than 0.
 If str1 is equal to str2, the return value
is 0
strncmp() compares the first n characters int strncmp(const char* str1, const
from the two null-terminated char* str2, size_t num);
strings and returns an integer num is the number of characters to
based on the outcome. compare.
strcpy() copy one string to another char* strcpy(char* dest, const char*
src);
dest: Pointer to the destination array
where the content is to be copied.
src: string which will be copied.
strcpy() function returns a pointer
pointing to the output string.
strncpy() Copies at most n bytes of src har* strncpy( char* dest, const char*
to dest src, size_t n );
strchr() find the first occurrence of a char *strchr(const char *str, size_t c);
character in a string

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 6 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

str: specifies the pointer to the null-


terminated string to be searched in.
ch: specifies the character to be searched
for.
It returns a pointer to the first
occurrence of the character in the
string.
strstr() to search the first occurrence char *strstr (const char *s1, const
of a substring in another string char *s2);
s1: This is the main string to be
examined.
s2: This is the sub-string to be searched
in the s1 string.
If the s2 is found in s1, this function
returns a pointer to the first character of
the s2 in s1, otherwise, it returns a null
pointer.
It returns s1 if s2 points to an empty
string.

C Program to demonstrate Built-in String Functions


// C Program to demonstrate string operations
#include <stdio.h>
#include<string.h>

int main()
{
//STRING CONCATINATION
char dest[50] = "This is an";
char src[50] = " example";
strcat(dest, src); // concatenating src at the end of dest
printf("String Concatenation Result: %s", dest);

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 7 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

//STRING n CONCATINATION
char dest1[50] = "This is an";
char src1[50] = " example";
strncat(dest1, src1, 5); // concatenating src at the end of dest
printf("\nString n Concatenation Result: %s", dest1);

//STRING LENGTH
char str[] = "DataStructures";
size_t length = strlen(str);
printf("\nString Length: %zu\n", length); //to print size_t result

//STRING COMPARE
char str1[] = "Hello";
char str2[] = "How";
char str3[] = "Hello";
int result1 = strcmp(str1, str2);
int result2 = strcmp(str2, str3);
int result3 = strcmp(str1, str3);
printf("\nComparison of str1 and str2: %d\n", result1);
printf("Comparison of str2 and str3: %d\n", result2);
printf("Comparison of str1 and str1: %d\n", result3);

//STRING n COMPARE
int result11 = strncmp(str1, str2, 2);
int result12 = strncmp(str2, str3, 2);
int result13 = strncmp(str1, str3, 2);
printf("\nComparison of str1 and str2: %d\n", result11);
printf("Comparison of str2 and str3: %d\n", result12);
printf("Comparison of str1 and str1: %d\n", result13);

//STRING COPY

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 8 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

char source[] = "Data Structures";


char dest2[20];
strcpy(dest2, source);
printf("\nSource: %s\t\t", source);
printf("Destination: %s\n", dest2);

//STRING n COPY
char source1[] = "Data Structures";
char dest22[20];
strncpy(dest22, source, 6);
printf("Source: %s\t\t", source1);
printf("Destination: %s\n", dest22);

//STRING CHR TO SEARCH CHARACTER


char str9[] = "Data Structures";
char ch = 'S';
char *result = strchr(str9, ch);
if (result != NULL)
printf("The character '%c' is found at index %ld\n", ch, result - str9);
else
printf("The character '%c' is not found in the string\n", ch);

// STRING SEARCH
char s1[] = "Data Structures";
char s2[] = "ruct";
char *result5;
result5 = strstr(s1, s2);
if (result5 != NULL)
printf("Substring found: %s\n", result5);
else
printf("Substring not found.\n");

return 0;

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 9 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

Output:
String Concatenation Result: This is an example
String n Concatenation Result: This is an exam
String Length: 14
Comparison of str1 and str2: -10 Comparison of str2 and str3: 10
Comparison of str1 and str1: 0

Comparison of str1 and str2: -10 Comparison of str2 and str3: 10


Comparison of str1 and str1: 0

Source: Data Structures Destination: Data Structures


Source: Data Structures Destination: Data S

The character 'S' is found at index 5 Substring found: ructures

C Program to find String Length without using Built-in Function


#include <stdio.h>

int stringLength(const char *str) {


int length = 0;

// Iterate through the characters until the null character is encountered


while (str[length] != '\0') {
length++;
}
return length;
}

int main() {
char myString[] = "Hello, World!";
int length = stringLength(myString);

printf("Length of the string: %d\n", length);

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 10 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

return 0;
}
Output: Length of the string: 13

C Program to implement String Concatenation without using Built-in


Function
#include<stdio.h>
#include<string.h>
void concat(char[], char[]);
int main()
{
char s1[50], s2[30];
printf("\nEnter String 1 :");
gets(s1);
printf("\nEnter String 2 :");
gets(s2);
concat(s1, s2);
printf("\n Concatenated string is :%s", s1);
return (0);
}
void concat(char s1[], char s2[]) {
int i, j;
i = strlen(s1);
for (j = 0; s2[j] != '\0'; i++, j++) {
s1[i] = s2[j];
}
s1[i] = '\0';
}
Output:
Enter String 1 :Hello Enter String 2 :World
Concatenated string is :Hello World

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 11 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

C Program to implement String Comparison without using Built-in Function


#include <stdio.h>
int stringCompare(const char *str1, const char *str2) {
while (*str1 != '\0' && *str2 != '\0') {
if (*str1 != *str2) {
return 0; // Not equal
}
str1++;
str2++;
}

// Check if both strings have reached the end simultaneously


if (*str1 == '\0' && *str2 == '\0') {
return 1; // Equal
} else {
return 0; // Not equal
}
}

int main() {
char str1[20];
char str2[20];

printf("Enter the first string : ");


scanf("%s",str1);
printf("Enter the second string : ");
scanf("%s",str2);

if (stringCompare(str1, str2)) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}
return 0;

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 12 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

}
Output:
Enter the first string : Hello Enter the second string : Hello
Strings are equal.
Enter the first string : Hello Enter the second string : hello
Strings are not equal.

C Program to implement String Copy without using Built-in Function


#include <stdio.h>

void stringCopy(const char *source, char *destination) {


while (*source != '\0')
{
*destination = *source;
source++;
destination++;
}
*destination = '\0';
}

int main() {
char source[20];
char destination[20];
printf("Enter the first string : ");
gets(source);
stringCopy(source, destination);
printf("Copied String: ");
puts(destination);
return 0;
}
Output: Enter the first string : Hello World
Copied String: Hello World

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 13 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

1.6 Stacks
1.6.1 Definition
 A stack is a linear structure in which items may be added or removed only at one end called
the top of the stack (TOP). Stacks are sometimes known as LIFO (last in, first out) lists.
 As the items can be added or removed only from the top i.e. the last item to be added to a
stack is the first item to be removed.
 The two basic operations associated with stacks are:
o Push: is the term used to insert an element into a stack.
o Pop: is the term used to delete an element from a stack.

 All insertions and deletions take place at the same end, so the last element added to the
stack will be the first element removed from the stack.
 When a stack is created, the stack base remains fixed while the stack top changes as
elements are added and removed. The most accessible element is the top and the least
accessible element is the bottom of the stack.

1.6.2 Representation
 Let us consider a stack with N elements capacity. This is called as the size of the stack.
 The number of elements to be added should not exceed the maximum size of the stack.
 If we attempt to add new element beyond the maximum size, we will encounter a stack
overflow condition.
 Similarly, you cannot remove elements beyond the base of the stack. If such is the case,
we will reach a stack underflow condition (an empty stack).
 When an element is added to a stack, the operation is performed by push.
 The removal of an element is performed by the pop operation.

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 14 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

Basic features of Stack


1. Stack is an ordered list of similar data type.
2. Stack is a LIFO (Last in First out) structure or we can say FILO (First in Last out).
3. push() function is used to insert new elements into the Stack and pop() function is used to
remove an element from the stack.
4. Both insertion and removal are allowed at only one end of Stack called Top.
5. Stack is said to be in Overflow state when it is completely full and is said to be in Underflow
state if it is completely empty.

Stack Using Array


 A stack data structure can be implemented using one dimensional array. But stack
implemented using array, can store only fixed number of data values.
 This implementation is very simple, just define a one dimensional array of specific size
and insert or delete the values into that array by using LIFO principle with the help of a
variable 'top'.
 Initially top is set to -1. Whenever an element is to be inserted into the stack, increment the
top value by one and then insert.
 Whenever an element is to be deleted from the stack the stack, then delete the top value
and decrement the top value by one.

1.7.3. Array representation of Stack


Stack Implementation
 Using static arrays
 Using linked list (Dynamic Arrays)

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 15 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

1.7.4. Stack Operations


 A stack can be implemented using array as follows.
push(value): Inserting value into the stack
 In a stack, push() is a function used to insert an element into the stack. In a stack, the new
element is always inserted at top position.
 Push function takes one integer value as parameter and inserts that value into the stack.
We can use the following algorithm to push an element on to the stack.

Algorithm:
Step 1: Check whether stack is FULL. (top == SIZE-1)
Step 2: If it is FULL, then display "Stack is FULL!!! Stack overflow!!!" and terminate the function.
Step 3: If it is NOT FULL, then increment top value by one (top++) and set stack[top] to value
(stack[top] = value).

pop(): Delete a value from the Stack


 In a stack, pop() is a function used to delete an element from the stack. In a stack, the
element is always deleted from top position.
 Pop function does not take any value as parameter. We can use the following algorithm to
pop an element from the stack.

Algorithm:
Step 1: Check whether stack is EMPTY. (top == -1)
Step 2: If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and terminate
the function.
Step 3: If it is NOT EMPTY, then delete stack[top] and decrement top value by one (top--).

display(): Displays the elements of a Stack


 We can use the following algorithm to display the elements of a stack.

Algorithm:
Step 1: Check whether stack is EMPTY. (top == -1)
Step 2: If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 16 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

Step 3: If it is NOT EMPTY, then define a variable 'i' and initialize with top. Display stack[i] value
and decrement i value by one (i--).
Step 3: Repeat above step until i value becomes '0'.

Example
 Empty stack (Refer Fig. A)
 Push element 1 (Refer Fig. B)
 Push element 2 into stack (Refer Fig. C)
 Push element 3 into stack (Refer Fig. D)
 Pop (last element will be removed pointed by top) (Refer Fig. E)

A B C D E

1.7.5. Implementation of stack operations using array


Develop a menu driven Program in C for the following operations on STACK of
Integers (Array Implementation of Stack with maximum size MAX)
a) Push an Element on to Stack
b) Pop an Element from Stack
c) Demonstrate how Stack can be used to check Palindrome
d) Demonstrate Overflow and Underflow situations on Stack
e) Display the status of Stack
f) Exit

Support the program with appropriate functions for each of the above operations

Program
#include <stdio.h>
#include <stdlib.h>

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 17 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

#define MAX 5

int stack[MAX];
int top = -1;

void push(int element)


{
if (top == MAX - 1)
{
printf("Stack Overflow! Cannot push more elements.\n");
}
else
{
stack[++top] = element;
printf("%d pushed onto the stack.\n", element);
}
}

int pop()
{
if (top == -1)
{
printf("Stack Underflow! Cannot pop from an empty stack.\n");
return -1;
}
else
{
int ele = stack[top--];
return ele;
}
}

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 18 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

int isPalindrome()
{
int i, j;
for (i = top, j = 0; i >= j; i--, j++)
{
if (stack[i] != stack[j])
{
return 0; // Not a palindrome
}
}
return 1; // Palindrome
}

void displayStack()
{
if (top == -1) {
printf("Stack is empty.\n");
} else
{
printf("Stack elements: ");
for (int i = top; i >=0; i--)
printf("%d\t", stack[i]);
printf("\n");
}
}

int main()
{
int choice, element;
do {
printf("\n----- Menu -----\n");

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 19 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

printf("1. Push an Element\n");


printf("2. Pop an Element\n");
printf("3. Check Palindrome\n");
printf("4. Display Stack Status\n");
printf("5. Exit");
printf("\n----------------\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice)
{
case 1:
printf("Enter the element to push: ");
scanf("%d", &element);
push(element);
break;

case 2:
int val=pop();
printf("%d popped from the stack.\n", val);
break;

case 3:
if (isPalindrome())
printf("The stack is a palindrome.\n");
else
printf("The stack is not a palindrome.\n");
break;

case 4:
displayStack();
break;

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 20 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

case 5:
printf("Exiting the program.\n");
break;

default:
printf("Invalid choice! Please enter a valid option.\n");
}
} while (choice != 5);
return 0;
}

1.7.6. Stack using Dynamic Arrays


• Limitations of Stack
o Can run out of space when stack size is set too small
o Can waste memory if stack size set too large

Overflow/Underflow:
 No limitation on the capacity of a linked stack and hence no overflow condition.
 Underflow or empty condition occurs when top==NULL.

Stack using Linked list


 A stack can be represented as a linked list (using a singly linked list or one way list).
 The data field stores the elements of the stack and the link field hold pointers to the
neighbouring elements of the stack.
 The start pointer behaves as the top pointer and NULL pointer in the last node indicates
the bottom of the stack.
 In a stack push and pop operations are performed at one end called top.
 We can perform similar operations at one end of list using top pointer.

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 21 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

 Example

C Program to Implement Stack Operations using Dynamic Memory


Allocation
#include <stdio.h>
#include <stdlib.h>
#define MAX 5

struct node
{
int data;
struct node *link;
}*top = NULL;

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 22 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

void push(int);
int pop();
void Stack_Empty();
void Stack_Full();
void Display();
int Stack_Count();
void Destroy();
void Print_Top();

int main()
{
int choice, val;
while (1)
{
printf("\n1. PUSH an element \n");
printf("2. POP an element \n");
printf("3. Check if Stack is Empty \n");
printf("4. Check if Stack is Full \n");
printf("5. Display Elements present in Stack \n");
printf("6. Destroy Stack \n");
printf("7. Print Top of the Stack \n");
printf("8. Exit \n");
printf("Enter your choice: ");
scanf("%d",&choice); // Reading choice from keyboard
switch (choice)
{
case 1:
printf("\nEnter value to push into the stack : ");
scanf("%d",&val);
push(val);
break;

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 23 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

case 2:
val=pop();
printf("\nDeleted Node Value is %d : ", val);
break;

case 3:
Stack_Empty();
break;

case 4:
Stack_Full();
break;

case 5:
Display();
break;

case 6:
Destroy();
break;

case 7:
Print_Top();
break;

case 8: exit(0);

default: printf("Choice is not matching try again\n");


} // End of switch case
} // End of while loop
} // End of main program

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 24 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

void push(int val) // to insert elements in stack


{
int count;
struct node *temp;
temp = (struct node*)malloc(sizeof(struct node));
count = Stack_Count();
if (count == MAX) // Checking is no of nodes reached stack size
{
printf("STACK FULL\n");
}
else
{
temp->data = val;
temp->link = top;
top = temp;
}
}

int pop() // to delete elements from stack


{
struct node *temp;
int val;
if (top==NULL)
printf("**Stack is Empty**\n");
else
{
temp = top;
val=temp->data;
top = top->link;
free(temp);
}

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 25 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

return val;
}

void Stack_Empty() // to check if stack is empty


{
if (top == NULL)
printf("Stack is Empty\n");
else
printf("Elements are Present, Stack is not Empty \n");
}

void Stack_Full() // to check if stack is full


{
int count;
count = Stack_Count();
if (count == MAX)
printf("Stack is Full\n");
else
printf("Stack is not Full \n");
}

void Display() // to count the number of elements


{
int count = 0;
struct node *temp;

temp = top;
if (top == NULL)
printf("\n**Stack is Empty**\n");
else
{
printf("Contents of the Stack\n");

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 26 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

while (temp!= NULL)


{
printf(" %d\t",temp->data);
temp = temp->link;
count++;
}
}
printf("\nSize of Stack is %d \n",count);
}

int Stack_Count()
{
int count = 0;
struct node *temp;
temp = top;
while (temp!= NULL)
{
temp = temp->link;
count++;
}
return count;
}

void Destroy() // to destroy the stack


{
struct node *temp;
temp = top;
while (temp!= NULL)
{
temp = temp->link;
}
printf("Stack Destroyed\n");

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 27 of 28


Data Structures and Applications (BCS304) Module 2: Stacks and Queues

void Print_Top() // to print top element of stack


{
if (top == NULL)
printf("\n**Top is not available for an EMPTY Stack**\n");
else
printf("\nTop of the stack is %d \n",top->data);
}

Department of CSE, Vemana IT Prepared by: Dr. Kantharaju H C Page 28 of 28

You might also like