Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

DS JAVA_5th Lab Program

Uploaded by

janakirampilli70
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

DS JAVA_5th Lab Program

Uploaded by

janakirampilli70
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

4.

Stacks and Queues 43

for( int i=0; i < n; i++ )


que.addLast(str.charAt(i));

for( int i=n-1; i > n/2; i-- )


if( str.charAt(i) != que.removeFirst() ) return false;

return true;
}
}

Linked Stack
21. Write Java programs to implement the following using a singly linked list.
(a) Stack ADT
(b) Queue ADT
Another way to represent a stack is by using a linked list. A stack can be represented by using nodes of
the linked list. Each node contains two fields: data (info) and next (link). The data field of each
node contains an item in the stack and the corresponding next field points to the node containing the
next item in the stack. The next field of the last node is null – that is, the bottom of the stack. The
top refers to the topmost node (the last item inserted) in the stack. The empty stack is represented by
setting top to null. Because the way the nodes are pointing, push and pop operations are easy to
accomplish. Program 21(a) is a complete listing, demonstrating the push and pop operations of a stack
using singly linked list.

Program 21(a): Linked Implementation of a Stack


class Node
{ int data; // data item
Node next; // next node in linked-stack
Node( int d ) // constructor
{ data = d; } // next is automatically set to null
}
class LinkedStack
{
Node top; // top refers to top-node
Node p; // p refers to current node
public void push(int item) // add item onto stack
{
p = new Node(item); // create new node
p.next = top; // new node refers to old top
top = p; // top refers to new node
}
public Node pop() // remove a node from the stack
{
if( isEmpty() )
{ System.out.println("Stack is empty");
return null;
}
Node tmp = top; // tmp saves reference to top node
top = tmp.next; // now, top refers to next node of old top
44 Lab Manual Data Structures through Java

return tmp; // return the popped item


}
public Node peek() // get top node from the stack, without deleting
{
if( isEmpty() )
{ System.out.println("Stack is empty");
return null;
}
return top;
}
public void displayStack()
{
p = top; // p refers to top
System.out.print("\nContents of Stack: [ ");
while( p != null ) // start printing from top of stack to bottom of stack
{
System.out.print(p.data + " "); // print data
p = p.next; // move to next node
}
System.out.println("]");
}
public boolean isEmpty() // true if stack is empty
{ return (top == null); }
}
///////////////////////// LinkedStackDemo.java /////////////////
class LinkedStackDemo
{
public static void main(String[] args)
{
LinkedStack stk = new LinkedStack(); // create stack object
Node item; // item stores popped node
stk.push(20); // add 20, 35, 40 to stack
stk.push(35);
stk.push(40);
stk.displayStack(); // print contents of stack
item = stk.pop(); // remove a node from the top and print it
if( item != null )
{
System.out.println("Popped item: " + item.data);
stk.displayStack();
}
stk.push(65); // insert 65, 70, 75
stk.push(70);
stk.push(75);
stk.displayStack(); // display contents of stack
item = stk.pop(); // remove a node from the top and display it
if( item != null )
{
System.out.println(“Popped item: ” + item.data);
stk.displayStack();
}
System.out.println(“peek(): ” + stk.peek());// get top item
4. Stacks and Queues 45

stk.push(90); // insert 90
stk.displayStack();
}
}
Output from LinkedStack operations program:
Contents of Stack: [ 40 35 20 ]
Popped item: 40
Contents of Stack: [ 35 20 ]
Contents of Stack: [ 75 70 65 35 20 ]
Popped item: 75
peek(): 70
Contents of Stack: [ 70 65 35 20 ]
Contents of Stack: [ 90 70 65 35 20 ]

Linked Queue
In contiguous storage (using arrays), queues were harder to manipulate than were stacks. It causes
difficulties to handle full queues and empty queues. It is for queues that linked storage really comes
into its own. The linked implementation has two advantages over the array implementation: (1) it is
faster – locations for insertion and deletion are same – at the back and at the front, and (2) it wastes no
space – removed nodes are deleted by the automatic garbage collector process.
Linked queues are just as easy to handle as are linked stacks. This section presents a queue
implementation which makes use of the singly linked list. We keep two pointers, front and rear. The
operations of LinkedQueue class is given Program 21(b) and LinkedQueue class is tested in
Program 21(c).

Program 21(b): A LinkedQueue Class


public class LinkedQueue
{
class Node
{ Object data;
Node next;

Node(Object item) // constructor


{ data = item; }
}
Node front, rear;
int count;
public void insert(Object item)
{
Node p = new Node(item);
if(front == null) // queue is empty; insert first item
{ front = rear = p;
rear.next = null;
}

if(front == rear) // queue contains one item; insert second item


{ rear = p;
front.next = rear;
rear.next = null;
}
46 Lab Manual Data Structures through Java

else // queue contains 2 or more items


{ rear.next = p; // old rear.next refers to p
rear = p; // new rear refers to p
rear.next = null;
}
count++; // increment queue size
}
public Object remove()
{ if(isEmpty())
{ System.out.println("Q is empty"); return null; }
Object item = front.data;
front = front.next;
count--; // decrement queue size
return item;
}
public boolean isEmpty()
{ return (front == null); }
public Object peek()
{ return front.data; }
public int size()
{ return count; }

public void display()


{ Node p = front;
System.out.print("Linked Q: ");
if(p == null) System.out.println("empty");
while( p != null )
{
System.out.print(p.data + " ");
p = p.next;
}
System.out.println();
}
}

Program 21(c): Testing LinkedQueue Class

class LinkedQueueDemo
{ public static void main(String[] args)
{
LinkedQueue q = new LinkedQueue();
q.display();
q.insert('A');
q.insert('B');
q.insert('C');
q.insert('D');
q.display();
System.out.println("delete(): " + q.remove());
q.display();
System.out.println("peek(): " + q.peek());
q.insert('E');
q.insert('F');
4. Stacks and Queues 47

System.out.println("delete(): " + q.remove());


q.display();
System.out.println("size(): " + q.size());
}
}

Here is the output of this program:


Linked Q: empty
Linked Q: A B C D
remove(): A
Linked Q: B C D
peek(): B
remove(): B
Linked Q: C D E F
size(): 4

Deque ADT
22. Write Java programs to implement the deque (double ended queue) ADT using
(a) Array
(b) Doubly linked list.

A deque is a double-ended queue. You can insert items at either end and delete them from either end.
Methods are addFirst(), addLast(), removeFirst() and removeLast().
If you restrict yourself to addFirst() and removeFirst() (or their equivalents on the right),
then the deque acts like a stack. If you restrict yourself to addFirst() and removeLast() (or the
opposite pair), then it acts like a queue.
A deque provides a more versatile data structure than either a stack or a queue, and is sometimes
used in container class libraries to serve both purposes. However, it is not used as often as stacks and
queues.
The deque is maintained by either an array or linked list with pointers first and last which
point to the two ends of the deque. Such a structure is represented by the following figure.

first last

Deletion Insertion
Insertion Deletion

The methods of deque ADT are as follows:


addFirst(Object) Inserts an item at the left side of deque.
addLast(Object) Inserts an item at the right side of deque.
removeFirst() Deletes an item from the left of deque.
removeLast() Deletes an item from the right of deque.
getFirst() Returns an item from the left, without deleting the item.
getLast() Returns an item from right, without deleting the item.
size() Returns the current number of items in the deque.
isEmpty() Returns true, if deque is empty else returns false.

You might also like