-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java~
More file actions
105 lines (95 loc) · 2.53 KB
/
Stack.java~
File metadata and controls
105 lines (95 loc) · 2.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
Some chnages
*/
/**
*
* @author ameya
*/
import java.util.*;
//Node class is the structure of node of stack..
class Node{
//data is the value to be stored at each node
int data;
//pointer to next node
Node link;
//Default constructor
public Node(){
data=0;
link=null;
}
//Parameterized constructor
public Node(int num,Node next){
this.data=num;
this.link=next;
}
}
//this class contains all the operation to be performed on the stack....
class stack_function{
Node start=new Node();
stack_function()
{
start=null;
}
//method for inserting node(push) in the stack....
void push(int num)
{
Node nnode = new Node(num,null);
if(start==null)
{
start=nnode;
}else
{
nnode.link=start;
start=nnode;
}
}
// pop method for removing the top element(pop) from the stack
void pop()
{
if(start==null)
{
System.out.println("The stack is already empty");}
else{
Node ptr = new Node();
ptr=start;
start=ptr.link;
}
}
//method for traversing the stack..it will print the elements of the list...
void traverse_Stack()
{
if(start==null)
System.out.println("Oops.....The stack is empty...!! ");
else
{
System.out.println("The stack has the following data:");
Node ptr =new Node();
ptr=start;
while(ptr!=null)
{
System.out.print("----------");System.out.println("");
System.out.print("| ");System.out.print(ptr.data+" ");System.out.print(" |");System.out.println("");
ptr=ptr.link;
}
}
}
}
//class conatining the main method
public class Stack {
public static void main(String[] args) {
//object of stack_function to perform operations on the stack
stack_function obj =new stack_function();
//various operations are performed by calling the method..
obj.push(5);
obj.push(2);
obj.push(4);
obj.push(7);
obj.push(6);
obj.push(12);
obj.pop();
obj.traverse_Stack();
}
}