Wednesday, March 11, 2015

Linked List and Implementation of Stack and Vector Swap in java



Searching Linked List
 
import java.util.LinkedList;
public class Main
 {
   public static void main(String[] args) 
     {
      LinkedList lList = new LinkedList();
      lList.add("1");
      lList.add("2");
      lList.add("3");
      lList.add("4");
      lList.add("5");
      lList.add("2");
      System.out.println("First index of 2 is:"+
      lList.indexOf("2"));
      System.out.println("Last index of 2 is:"+ 
      lList.lastIndexOf("2"));
   }
}
 
Implementation of Stack
 
public class MyStack
 {
   private int maxSize;
   private long[] stackArray;
   private int top;
   public MyStack(int s) 
   {
      maxSize = s;
      stackArray = new long[maxSize];
      top = -1;
   }
   public void push(long j) 
   {
      stackArray[++top] = j;
   }
   public long pop() 
   {
      return stackArray[top--];
   }
   public long peek() 
   {
      return stackArray[top];
   }
   public boolean isEmpty() 
   {
      return (top == -1);
   }
   public boolean isFull() 
   {
      return (top == maxSize - 1);
   }
   public static void main(String[] args) 
   {
      MyStack theStack = new MyStack(10); 
      theStack.push(10);
      theStack.push(20);
      theStack.push(30);
      theStack.push(40);
      theStack.push(50);
      while (!theStack.isEmpty()) 
       {
         long value = theStack.pop();
         System.out.print(value);
         System.out.print(" ");
      }
      System.out.println("");
   }
}
 
Vector Swap
 
import java.util.Collections;
import java.util.Vector;
public class Main 
  {
   public static void main(String[] args) 
   {
      Vector v = new Vector();
      v.add("1");
      v.add("2");
      v.add("3");
      v.add("4");
      v.add("5");
      System.out.println(v);
      Collections.swap(v, 0, 4);
      System.out.println("After swapping");
      System.out.println(v);
   }
}

No comments:

Post a Comment