Home > Back-end >  Stack Array Data Structure using Java
Stack Array Data Structure using Java

Time:12-21

I am trying to write a stack code using Java for getting browsing history for 100 data. I wrote this code but I am not sure this program satisfies first in last out rule and also most importantly I don't want to write lastvisit = browsing.pop(); for 100 times for 100 data. What can I do for it?

import java.util.Stack;

public class Browser {
    
    public static void main(String[] args) {
       
        Stack<String> browsing = new Stack<>();

        
        browsing.push("google.com");
        browsing.push("facebook.com");
        browsing.push("twitter.com");
        browsing.push("youtube.com");

        System.out.println("Browsing History "   browsing);
        System.out.println();

        
        String lastvisit = browsing.pop();  
        System.out.println("lastvisit "   lastvisit);
        System.out.println("Browsing History "   browsing);
        System.out.println();

       
        lastvisit = browsing.pop();
        System.out.println("lastvisit "   lastvisit);
        System.out.println("Browsing History "   browsing);
        lastvisit = browsing.pop();  
        System.out.println("lastvisit "   lastvisit);
        System.out.println("Browsing History "   browsing);
    }   
}

CodePudding user response:

The JDK's Stack class indeed implements the "first in last out" (more commonly known as "last in first out", or LIFO) rule.

One way to go over the entire history would be to loop over the stack until it's empty:

while (!browsing.empty()) {
    String lastvisit = browsing.pop();  
    System.out.println("lastvisit "   lastvisit);
    System.out.println("Browsing History "   browsing);
    System.out.println();
}

CodePudding user response:

I updated the code with string array and added @Mureinik 's answer. Final clean code:

import java.util.*; 
import java.util.Stack;

public class Browser {
    
    public static void main(String[] args) {
           List<String> urls = Arrays.asList("facebook.com*mehmet.com google.com-kesimalioglu.com/youtube.com".split("[\\* /-]"));

        Stack<String> browsing = new Stack<String>();
    for(String str : urls)
        browsing.add(str);
        
        

        System.out.println("Browsing History "   browsing);
        System.out.println();

        
        while (!browsing.empty()) {
    String lastvisit = browsing.pop();  
    System.out.println("lastvisit "   lastvisit);
    System.out.println("Browsing History "   browsing);
    System.out.println();
}

    }
    
}
  • Related