Java array implementation stack and queue __ data structure (Java edition)

Source: Internet
Author: User
Array stack: Public
class Stack {
	private long[] Stackarray;
	private int top;
	private int maxSize;
	
	Public Stack (int maxSize) {
		this.maxsize = maxSize;
		top =-1;
		Stackarray = new Long[maxsize];
	}
	public void push (Long value) {
		Stackarray[++top] = value;
		maxsize++;
	}
	public long POPs () {return
		stackarray[top--];
	}
	public Boolean IsEmpty () {return top
		= = 1;
	}
	public Boolean isfull () {return
		maxSize = = = (top+1);
	}
	Public long Gettopvalue () {return
		stackarray[top];
	}
}
Test class:
<pre name= "code" class= "Java" >class stackapp{public
	static void Main (String args[]) {
		Stack stack = new stack (a);
		Stack.push (1);
		Stack.push (2);
		Stack.push (3);
		Stack.push (4);
		
		while (!stack.isempty ()) {
			Long value = Stack.pop ();
			System.out.println ("" "+value);
		} While
		
	} 
}

Array queues:
Class queue{
Private long[] array;
private int front;
private int rear;
private int nelements;
private int maxSize;

Public queue (int s) {
MaxSize = s;
Array = new Long[maxsize];
Front = 0;
Rear =-1;
nelements = 0;
}
public void Insert (Long value) {
if (rear = = maxSize-1) {
Rear =-1;
}
Array[++rear] = value;
nelements++;
}
Public long Remove () {
if (front+1 = = maxSize) {
Front = 0;
}
nelements--;
return array[front++];
}
Public long getfrontelement () {
return Array[front];
}
public Boolean IsEmpty () {
return (nelements = 0);
}
public Boolean isfull () {
return (MaxSize = = nelements);
}
public int getnelements () {
return nelements;
}
}
Test class:
Class queueapp{
public static void Main (String args[]) {
Queue que = new Queue (10);
Que.insert (10);
Que.insert (20);
Que.insert (30);
Que.insert (40);
Que.insert (50);

while (!que.isempty ()) {
Long temp = Que.remove ();
System.out.println ("" +temp);
}
}
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.