0% found this document useful (0 votes)
105 views

Java Data Structure

The document provides code examples for common data structure operations in Java, including: 1) Summing the first n numbers using a stack. 2) Getting the first and last elements of a linked list. 3) Adding elements to the beginning and end of a linked list.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views

Java Data Structure

The document provides code examples for common data structure operations in Java, including: 1) Summing the first n numbers using a stack. 2) Getting the first and last elements of a linked list. 3) Adding elements to the beginning and end of a linked list.

Uploaded by

suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Java Data Structure - Programming Examples

Learn how to play with data structure in Java programming. Here are most commonly used examples:

1. How to print summation of n numbers?


2. How to get the first and the last element of a linked list?

. Page 61
3. How to add an element at first and last position of a linked list?
4. How to convert an infix expression to postfix expression?
5. How to implement Queue?
6. How to reverse a string using stack?
7. How to search an element inside a linked list?
8. How to implement stack?
9. How to swap two elements in a vector?
10. How to update a linked list?
11. How to get the maximum element from a vector?
12. How to execute binary search on a vector?
13. How to get elements of a LinkedList?
14. How to delete many elements from a linkedList?

How to print summation of n numbers?

Solution:

Following example demonstrates how to add first n natural numbers by using the concept of stack .

import java.io.IOException;

public class AdditionStack {


static int num;
static int ans;
static Stack theStack;
public static void main(String[] args)
throws IOException {
num = 50;
stackAddition();
System.out.println("Sum=" + ans);
}
public static void stackAddition() {
theStack = new Stack(10000);
ans = 0;
while (num > 0) {
theStack.push(num);
--num;
}
while (!theStack.isEmpty()) {
int newN = theStack.pop();
ans += newN;
}
}
}

class Stack {
private int maxSize;
private int[] data;
private int top;
public Stack(int s) {
maxSize = s;
data = new int[maxSize];
top = -1;
}
public void push(int p) {
data[++top] = p;
}

Page 62
public int pop() {
return data[top--];
}
public int peek() {
return data[top];
}
public boolean isEmpty() {
return (top == -1);
}
}

Result:

The above code sample will produce the following result.

Sum=1225

How to get the first and the last element of a linked list ?

Solution:

Following example shows how to get the first and last element of a linked list with the help
of linkedlistname.getFirst() and linkedlistname.getLast() of LinkedList class.

import java.util.LinkedList;

public class Main {


public static void main(String[] args) {
LinkedList lList = new LinkedList();
lList.add("100");
lList.add("200");
lList.add("300");
lList.add("400");
lList.add("500");
System.out.println("First element of LinkedList is :
" + lList.getFirst());
System.out.println("Last element of LinkedList is :
" + lList.getLast());
}
}

Result:

The above code sample will produce the following result.

First element of LinkedList is :100


Last element of LinkedList is :500

How to add an element at first and last position of a linked list?


Page 63
Solution:

Following example shows how to add an element at the first and last position of a linked list by using
addFirst() and addLast() method of Linked List class.

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");
System.out.println(lList);
lList.addFirst("0");
System.out.println(lList);
lList.addLast("6");
System.out.println(lList);
}
}

Result:

The above code sample will produce the following result.

1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5
0, 1, 2, 3, 4, 5, 6

How to convert an infix expression to postfix expression?

Solution:

Following example demonstrates how to convert an infix to postfix expression by using the concept of stack.

import java.io.IOException;

public class InToPost {


private Stack theStack;
private String input;
private String output = "";
public InToPost(String in) {
input = in;
int stackSize = input.length();
theStack = new Stack(stackSize);
}
public String doTrans() {
for (int j = 0; j < input.length(); j++) {
char ch = input.charAt(j);
switch (ch) {
case '+':
case '-':
gotOper(ch, 1);

Page 64
break;
case '*':
case '/':
gotOper(ch, 2);
break;
case '(':
theStack.push(ch);
break;
case ')':
gotParen(ch);
break;
default:
output = output + ch;
break;
}
}
while (!theStack.isEmpty()) {
output = output + theStack.pop();
}
System.out.println(output);
return output;
}
public void gotOper(char opThis, int prec1) {
while (!theStack.isEmpty()) {
char opTop = theStack.pop();
if (opTop == '(') {
theStack.push(opTop);
break;
}
else {
int prec2;
if (opTop == '+' || opTop == '-')
prec2 = 1;
else
prec2 = 2;
if (prec2 < prec1) {
theStack.push(opTop);
break;
}
else
output = output + opTop;
}
}
theStack.push(opThis);
}
public void gotParen(char ch){
while (!theStack.isEmpty()) {
char chx = theStack.pop();
if (chx == '(')
break;
else
output = output + chx;
}
}
public static void main(String[] args)
throws IOException {
String input = "1+2*4/5-7+3/6";
String output;
InToPost theTrans = new InToPost(input); output =
theTrans.doTrans(); System.out.println("Postfix
is " + output + '\n');
}
class Stack {
private int maxSize;
private char[] stackArray;

Page 65
private int top;
public Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
}

Result:

The above code sample will produce the following result.

124*5/+7-36/+
Postfix is 124*5/+7-36/+

How to implement Queue ?

Solution:

Following example shows how to implement a queue in an employee structure.

import java.util.LinkedList;

class GenQueue {
private LinkedList list = new LinkedList();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public boolean hasItems() {
return !list.isEmpty();
}
public int size() {
return list.size();
}
public void addItems(GenQueue q) {
while (q.hasItems())
list.addLast(q.dequeue());
}
}

public class GenQueueTest {

Page 66
public static void main(String[] args) {
GenQueue empList;
empList = new GenQueue();
GenQueue hList;
hList = new GenQueue();
hList.enqueue(new HourlyEmployee("T", "D"));
hList.enqueue(new HourlyEmployee("G", "B"));
hList.enqueue(new HourlyEmployee("F", "S"));
empList.addItems(hList);
System.out.println("The employees' names are:");
while (empList.hasItems()) {
Employee emp = empList.dequeue();
System.out.println(emp.firstName + " "
+ emp.lastName);
}
}
}

class Employee {
public String lastName;
public String firstName;
public Employee() {
}
public Employee(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}

class HourlyEmployee extends Employee {


public double hourlyRate; public
HourlyEmployee(String last, String first) {
super(last, first);
}
}

Result:

The above code sample will produce the following result.

The employees' name are:


T D
G B
F S

How to reverse a string using stack ?

Solution:

Following example shows how to reverse a string using stack with the help of user defined
method StringReverserThroughStack().

import java.io.IOException;

Page 67
public class StringReverserThroughStack {
private String input;
private String output;
public StringReverserThroughStack(String in)
{ input = in;
}
public String doRev() {
int stackSize = input.length();
Stack theStack = new Stack(stackSize);
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
theStack.push(ch);
}
output = "";
while (!theStack.isEmpty()) {
char ch = theStack.pop();
output = output + ch;
}
return output;
}
public static void main(String[] args)
throws IOException {
String input = "Java Source and Support";
String output;
StringReverserThroughStack theReverser =
new StringReverserThroughStack(input);
output = theReverser.doRev();
System.out.println("Reversed: " + output);
}
class Stack {
private int maxSize;
private char[] stackArray;
private int top;
public Stack(int max) {
maxSize = max;
stackArray = new char[maxSize];
top = -1;
}
public void push(char j) {
stackArray[++top] = j;
}
public char pop() {
return stackArray[top--];
}
public char peek() {
return stackArray[top];
}
public boolean isEmpty() {
return (top == -1);
}
}
}

Result:

The above code sample will produce the following result.

JavaStringReversal
Reversed:lasreveRgnirtSavaJ

Page 68
How to search an element inside a linked list ?

Solution:

Following example demonstrates how to search an element inside a linked list using
linkedlistname.indexof(element) to get the first position of the element and
linkedlistname.Lastindexof(elementname) to get the last position of the element inside the 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"));
}
}
Result:

The above code sample will produce the following result.

First index of 2 is: 1


Last index of 2 is: 5

How to implement stack?

Solution:

Following example shows how to implement stack by creating user defined push() method for
entering elements and pop() method for retriving elements from the 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;

Page 69
}
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("");
}
}

Result:

The above code sample will produce the following result.

50 40 30 20 10

How to swap two elements in a vector ?

Solution:

Following example .

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);
}

Page 70
}

Result:

The above code sample will produce the following result.

1 2 34 5
After swapping
5 2 34 1

How to update a linked list ?

Solution:

Following example demonstrates how to update a linked list by using listname.add() and listname.set()
methods of LinkedList class.
import java.util.LinkedList;

public class MainClass {


public static void main(String[] a) {
LinkedList officers = new LinkedList();
officers.add("B");
officers.add("B");
officers.add("T");
officers.add("H");
officers.add("P");
System.out.println(officers);
officers.set(2, "M");
System.out.println(officers);
}
}

Result:

The above code sample will produce the following result.

BBTHP
BBMHP

How to get the maximum element from a vector ?

Solution:

Following example demonstrates how to get the maximum element of a vector by using v.add() method of
Vector class and Collections.max() method of Collection class.

import java.util.Collections;

Page 71
import java.util.Vector;

public class Main {


public static void main(String[] args) {
Vector v = new Vector();
v.add(new Double("3.4324"));
v.add(new Double("3.3532"));
v.add(new Double("3.342"));
v.add(new Double("3.349"));
v.add(new Double("2.3"));
Object obj = Collections.max(v);
System.out.println("The max element is:"+obj);
}
}

Result:

The above code sample will produce the following result.

The max element is: 3.4324

How to execute binary search on a vector ?

Solution:

Following example how to execute binary search on a vector with the help of v.add() method of Vector
class and sort.Collection() method of Collection class.
import java.util.Collections;
import java.util.Vector;

public class Main {


public static void main(String[] args) {
Vector v = new Vector();
v.add("X");
v.add("M");
v.add("D");
v.add("A");
v.add("O");
Collections.sort(v);
System.out.println(v);
int index = Collections.binarySearch(v, "D");
System.out.println("Element found at : " + index);
}
}

Result:

The above code sample will produce the following result.

[A, D, M, O, X]
Element found at : 1

Page 72
How to get elements of a LinkedList?

Solution:

Following example demonstrates how to get elements of LinkedList using top() & pop() methods.

import java.util.*;

public class Main {


private LinkedList list = new LinkedList();
public void push(Object v) {
list.addFirst(v);
}
public Object top() {
return list.getFirst();
}
public Object pop() {
return list.removeFirst();
}
public static void main(String[] args) {
Main stack = new Main();
for (int i = 30; i < 40; i++)
stack.push(new Integer(i));
System.out.println(stack.top());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}

Result:

The above code sample will produce the following result.

39
39
38
37

How to delete many elements from a linkedList?

Solution:

Following example demonstrates how to delete many elements of linkedList using Clear() method.

import java.util.*;

public class Main {


public static void main(String[] args) {
LinkedList lList = new LinkedList();
lList.add("1");
lList.add("8");

Page 73
lList.add("6");
lList.add("4");
lList.add("5");
System.out.println(lList);
lList.subList(2, 4).clear();
System.out.println(lList);
}
}

Result:

The above code sample will produce the following result.

[one, two, three, four, five]


[one, two, three, Replaced, five]

You might also like