इस उदाहरण में, हम जावा में स्टैक डेटा संरचना को लागू करना सीखेंगे।
इस उदाहरण को समझने के लिए, आपको निम्नलिखित जावा प्रोग्रामिंग विषयों का ज्ञान होना चाहिए:
- जावा स्टैक क्लास
- जावा जेनरिक
उदाहरण 1: स्टैक को लागू करने के लिए जावा प्रोग्राम
// Stack implementation in Java class Stack ( // store elements of stack private int arr(); // represent top of stack private int top; // total capacity of the stack private int capacity; // Creating a stack Stack(int size) ( // initialize the array // initialize the stack variables arr = new int(size); capacity = size; top = -1; ) // push elements to the top of stack public void push(int x) ( if (isFull()) ( System.out.println("Stack OverFlow"); // terminates the program System.exit(1); ) // insert element on top of stack System.out.println("Inserting " + x); arr(++top) = x; ) // pop elements from top of stack public int pop() ( // if stack is empty // no element to pop if (isEmpty()) ( System.out.println("STACK EMPTY"); // terminates the program System.exit(1); ) // pop element from top of stack return arr(top--); ) // return size of the stack public int getSize() ( return top + 1; ) // check if the stack is empty public Boolean isEmpty() ( return top == -1; ) // check if the stack is full public Boolean isFull() ( return top == capacity - 1; ) // display elements of stack public void printStack() ( for (int i = 0; i <= top; i++) ( System.out.print(arr(i) + ", "); ) ) public static void main(String() args) ( Stack stack = new Stack(5); stack.push(1); stack.push(2); stack.push(3); System.out.print("Stack: "); stack.printStack(); // remove element from stack stack.pop(); System.out.println("After popping out"); stack.printStack(); ) )
आउटपुट
1 को सम्मिलित करते हुए 2 को सम्मिलित करते हुए 3 ढेर करें: 1, 2, 3, 1, 2 को बाहर निकालने के बाद,
उपरोक्त उदाहरण में, हमने जावा में स्टैक डेटा संरचना को लागू किया है।
अधिक जानने के लिए, स्टैक डेटा संरचना पर जाएँ।
उदाहरण 2: स्टैक वर्ग का उपयोग करके स्टैक को लागू करें
जावा एक निर्मित Stackवर्ग प्रदान करता है जिसका उपयोग स्टैक को लागू करने के लिए किया जा सकता है।
import java.util.Stack; class Main ( public static void main(String() args) ( // create an object of Stack class Stack animals= new Stack(); // push elements to top of stack animals.push("Dog"); animals.push("Horse"); animals.push("Cat"); System.out.println("Stack: " + animals); // pop element from top of stack animals.pop(); System.out.println("Stack after pop: " + animals); ) )
आउटपुट
ढेर: (कुत्ता, घोड़ा, बिल्ली) ढेर पॉप के बाद: (कुत्ता, घोड़ा)
उपरोक्त उदाहरण में, हमने Stackजावा में स्टैक को लागू करने के लिए कक्षा का उपयोग किया है । यहाँ,
- animal.push () - ढेर के शीर्ष पर तत्व डालें
- animal.pop () - ढेर के ऊपर से तत्व निकालें
ध्यान दें, हमने स्टैक बनाते समय कोण कोष्ठक का उपयोग किया है । यह दर्शाता है कि स्टैक सामान्य प्रकार का है।








