InterviewSolution
| 1. |
WordPile is an entity which can hold a maximum of 20 characters. The restriction is that a character can be added or removed from one end only. Some of the members of classes are given below: Class name: WordPile Data members/instance variables: ch[]: character array to hold the character elements capacity: integer variable to store the maximum capacity top: to point to the index of the topmost element Member functions/methods: WordPile (int cap): constructor to initialise the data member capacity = cap, top = -1 and create the WordPile void pushChar(char v): adds the character to the top of WordPile if possible, otherwise output a message “WordPile is full” charpopChar(): returns the deleted character from the top of the WordPile if possible, otherwise it returns ‘\\’ (a) Specify the class WordPile giving the details of the constructor, void pushChar(char) and char popChar().The main function and algorithm need not be written. (b) What is the name of the entity described above and state one of its applications? |
|
Answer» (a) import java. util. Scanner; class WordPile { char ch[]; int capacity; int top; public WordPile(int cap) { capacity=cap; top=-1; ch=new char[capacityj; } public void pushChar(char v) { if(top+1==capacity) System.out.println("WordPile is full"); else ch[++top]=v; } public char popChar() { if(top==-1) return '\\'; else return ch[top--]; } //main written so that the program can be executed public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.print("How many characters?”); int n=sc.nextInt(); if(n>20) n=20; WordPile obj=new WordPile(n); outer: while(true) { System.out.println("1. PushCharacter"); System.out.println("2. Pop Character"); System.out.print("Enter your choice:"); int choice=sc.nextInt(); switch(choice) { case 1: System.out.print("Enter thecharacter:"); char c=sc.next()charAt(0); obj.pushChar(c); break; case 2: c=obj.popChar(); if(c=='\\') System.out.println("Empty stack."); else System.out.println(c+" popped."); break; default: break outer; } } } } (b) The name of the entity described above is ‘Stack’. One of its applications is to reverse a string. |
|