Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Iterator;
- public class StackClient<Item> implements Iterable<Item> {
- private int N;
- private Node first;
- private class Node {
- //This is the primitive implementation of a linked list in Java.
- //defined a class named node with an "item" and a Node object "next".
- Item item;
- Node next;
- }
- public Item pop() {
- Item item = first.item;
- first = first.next;
- N--;
- return item;
- }
- public StackClient() {
- N = 0;
- first = null;
- }
- public void add(Item item) {
- Node oldfirst = first;
- first = new Node();
- first.item = item;
- first.next = oldfirst;
- }
- public boolean isEmpty() {
- return !iterator().hasNext(); //returns true if node reference is null
- }
- public int size() {
- return N;
- }
- public Iterator<Item> iterator() {
- return new ListIterator();
- }
- private class ListIterator implements Iterator<Item> {
- private Node current = first;
- public boolean hasNext() {
- // TODO Auto-generated method stub
- return current != null;
- }
- public Item next() {
- // TODO Auto-generated method stub
- Item item = current.item;
- current = current.next;
- return item;
- }
- public void remove() {
- }
- }
- public static StackClient<String> copy(StackClient<String> stackClient) {
- StackClient<String> resultStack = new StackClient<String>();
- StackClient<String> tempStack = new StackClient<String>();
- Iterator<String> iterator = stackClient.iterator();
- while (iterator.hasNext()) {
- tempStack.add(iterator.next());
- }
- Iterator<String> tempIterator = tempStack.iterator();
- while (tempIterator.hasNext()) {
- resultStack.add(tempIterator.next());
- }
- return resultStack;
- }
- public static StackClient<String> inverse(StackClient<String> stackClient) {
- StackClient<String> resultStack = new StackClient<String>();
- for (String name : stackClient){
- String a = stackClient.pop();
- resultStack.add(a);
- }
- return resultStack;
- }
- public static void main(String[] args) {
- StackClient<String> stack = new StackClient<String>();
- stack.add("Parsa");
- stack.add("pooria");
- stack.add("Paniz");
- System.out.println(stack.isEmpty());
- for (String string : stack) {
- System.out.print(string + " ");
- }
- StackClient<String> stackk = StackClient.copy(stack);
- for (String string : stackk) {
- System.out.print(string + " ");
- }
- StackClient<String> inverted = StackClient.inverse(stack);
- for (String string : stack) {
- System.out.print(string + " ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement