Sie sind auf Seite 1von 24

DATA STRUCTURES

1-QUEUE
1.1-What is Queue in Data Structure?

A Queue is a linear structure which follows a particular order in which the


operations are performed. The order is First In First Out (FIFO). A good example of a
queue is any metrobus. If you first get in to metrobus, you get off last from metrobus.

1.1.1-What is enQueue Function in Queue?

Addition of an element to the queue. Adding an element will be performed


after checking whether the queue is full or not. If rear < n which indicates that the
array is not full then store the element at arr[rear] and increment rear by but if rear ==
n then it is said to be an Overflow condition as the array is full.
enQueue(q, x)
1) While stack1 is not empty, push everything from stack1 to stack2.
2) Push x to stack1 (assuming size of stacks is unlimited).
3) Push everything back to stack1.
Here time complexity will be O(n)

Code Example

static void enQueue(int x)


{
// Move all elements from s1 to s2
while (!s1.isEmpty())
{
s2.push(s1.pop());
//s1.pop();
}

// Push item into s1


s1.push(x);

// Push everything back to s1


while (!s2.isEmpty())
{
s1.push(s2.pop());
//s2.pop();
}
}

1.1.2-What is deQueue Function in Queue?

Removal of an element from the queue. An element can only be deleted when
there is at least an element to delete i.e. rear > 0. Now, element at arr[front]can be
deleted but all the remaining elements have to shifted to the left by one position in
order for the dequeue operation to delete the second element from the left on
another dequeue operation.
deQueue(q)
1) If stack1 is empty then error
2) Pop an item from stack1 and return it
Here time complexity will be O(1)

Code Example

static int deQueue()


{
// if first stack is empty
if (s1.isEmpty())
{
System.out.println("Q is Empty");
System.exit(0);
}

// Return top of s1
int x = s1.peek();
s1.pop();
return x;
}

1.1.3 What is Front Function?

This function is used to reference the first or the oldest element of the queue
container. This function can be used to fetch the first element of a queue.

queuename.front()
Parameters :
No value is needed to pass as the parameter.
Returns :
Direct reference to the first element of the queue container.

Code Example

int main()
{
queue<int> myqueue;
myqueue.push(3);
myqueue.push(4);

// Queue becomes 3, 4

cout << myqueue.front(); // Output is 3.


return 0;
}

1.1.4 What is Rear Funtion?

This function is used to reference the last or the newest element of the queue
container. This function can be used to fetch the first element from the back of a
queue.

queuename.rear()
Parameters :
No value is needed to pass as the parameter.
Returns :
Direct reference to the last element of the queue container.

Code Example

int main()
{
queue<int> myqueue;
myqueue.push(3);
myqueue.push(4);

// Queue becomes 3, 4

cout << myqueue.rear(); // Output is 4.


return 0;
}

1.2- What is Queue Array List?


In queue, insertion and deletion happen at the opposite ends, so
implementation is not as simple as stack.
To implement a queue using array, create an array arr of size n and take two
variables front and rear both of which will be initialized to 0 which means the queue is
currently empty. Element rear is the index upto which the elements are stored in the
array and front is the index of the first element of the array.

For example:

We can create Queue using interface with ArrayList parameter:

interface Queue<T> {
Queue<T> enqueue(T ele);
T dequeue();
}

1.3-What is Queue Linked List?

In a linked queue, each node of the queue consists of two parts i.e. data part
and the link part. Each element of the queue points to its immediate next element in
the memory.

In the linked queue, there are two pointers maintained in the memory i.e. front pointer
and rear pointer. The front pointer contains the address of the starting element of the
queue while the rear pointer contains the address of the last element of the queue.

Insertion and deletions are performed at rear and front end respectively. If front and
rear both are NULL, it indicates that the queue is empty.

The linked representation of queue is shown in the following figure.

Before create Queue Link, we should Node class. In node we have one or more data
and one pointer next type.

Code Example

private Node first, last;

private class Node {


private T ele;
private Node next;
}

After that we can create an Queue object using node, node’s pointer and data value.
All new item will adding last pointer. That’s queue rule.
So that’s mean last item will be new item.

public QueueLinkedList() { }

public QueueLinkedList<T> enqueue(T ele)


{
Node current = last;
last = new Node();
last.ele = ele;

if (total++ == 0) first = last;


else current.next = last;
return this;
}

1.4-Diffirent Between Queue Array List and Queue Linked List


2-STACK
2.1-What is Stack in Data Structures?

Stack is an abstract data type with a bounded(predefined) capacity. It is a


simple data structure that allows adding and removing elements in a particular order.
Every time an element is added, it goes on the top of the stack and the only element
that can be removed is the element that is at the top of the stack, just like a pile of
objects.

2.1.1-What is Push and Pop Method in Stack?

Push the item into the stack, and pop the item out of the stack. A stack is a
limited access data structure - elements can be added and removed from the stack
only at the top. push adds an item to the top of the stack, pop removes the item from
the top. A helpful analogy is to think of a stack of books; you can remove only the top
book, also you can add a new book on the top.

PUSH()

stackname.push(value)
Parameters :
The value of the element to be inserted is passed as the parameter.
Result :
Adds an element of value same as that of
the parameter passed at the top of the stack.

Code Example

Input : mystack
mystack.push(6);
Output : 6

POP()

stackname.pop()
Parameters :
No parameters are passed.
Result :
Removes the newest element in the stackor basically the top element.

Code Example

Input : mystack = 0, 1, 2
mystack.pop();
Output : 0, 1
2.1.2-What is Top Method in Stack?

Stacks are a type of container adaptors with LIFO(Last In First Out) type of
working, where a new element is added at one end and (top) an element is removed
from that end only.

TOP()

stackname.top()
Parameters :
No value is needed to pass as the parameter.
Returns :
Direct reference to the top element of the stack container.

Code Example

Input : stackname.push(5);
stackname.push(1);
stackname.top();
Output : 1

2.1.3-What is Peek Method in Stack?

In computer science, peek is an operation on certain abstract data types,


specifically sequential collections such as stacks and queues, which returns the
value of the top ("front") of the collection without removing the element from the
collection.
PEEK()

Parameters: The method does not take any parameters.


Return Value: The method returns the element at the top of the Stack else returns
NULL if the Stack is empty.
Exception: The method throws EmptyStackException if the stack is empty.

Code Example

STACK.push("Welcome");
STACK.push("Home");
System.out.println("The element at the top of the" + " stack is: " +
STACK.peek());

Output: The element at the top of the stack is: To

2.2-What is Stack Array?

Stack - Array Implementation. Abstract idea of a stack: The stack is a very


common data structure used in programs. By data structure, we mean something
that is meant to hold data and provides certain operations on that data.

Code Example

private int arr[];


private int size;
private int index = 0;

public Stack(int size) {


this.size = size;
arr = new int[size];
}
2.3-What is Stack Linked List ?
A stack can be easily implemented through the linked list.
In stack Implementation, a stackcontains a top pointer. which is “head” of
the stackwhere pushing and popping items happens at the head of the list.

Code Example

struct Node {
int data;
struct Node* link;
};
struct Node* top;

2.4-Diffirent Between Stack Array and Stack Linked List


2.5-What is Stack Dynamic Array?

A stack-dynamic array is one in which the subscript ranges


are dynamicallybound, and the storage allocation is dynamic “during execution.”
Once bound they remain fixed during the lifetime of the variable. Advantages:
Flexibility. The size of the array is known at bound time.

Code Example

class DynamicStack {
private int top;
private int capacity;
private int[] array;

public DynamicStack(int cap) {


capacity = cap;
array = new int[capacity];
top = -1;
}

3-HASHTABLE

3.1-What is HashTable in Java?

Hashtable was part of the original java.util and is a concrete implementation of


a Dictionary.

However, Java 2 re-engineered Hashtable so that it also implements the Map


interface. Thus, Hashtable is now integrated into the collections framework. It is
similar to HashMap, but is synchronized.

Like HashMap, Hashtable stores key/value pairs in a hash table. When using a
Hashtable, you specify an object that is used as a key, and the value that you want
linked to that key. The key is then hashed, and the resulting hash code is used as the
index at which the value is stored within the table.

Following is the list of constructors provided by the HashTable class.


3.1.1- What is HashTable Methods?

1-void clear( )

Resets and empties the hash table.

Code Example

HashSet hashSet = new HashSet();

hashSet.put(5);

hashSet.put(3);

hashSet.reset();

//Output: null

2-Object get(Object key)

Returns the object that contains the value associated with the key. If the key is not in
the hash table, a null object is returned.

Code Example

HashSet hashSet = new HashSet();

hashSet.put(5);

hashSet.put(3);

hashSet.get(1)

//Output: 3
3-boolean isEmpty( )

Returns true if the hash table is empty; returns false if it contains at least one key.

Code Example

HashSet hashSet = new HashSet();

hashSet.put(5);

hashSet.put(3);

hashSet.isEmpty();

//Output: false

4-Object put(Object value)

Inserts a key and a value into the hash table. Returns null if the key isn't already in
the hash table; returns the previous value associated with the key if the key is already
in the hash table.

Code Example

HashSet hashSet = new HashSet();

hashSet.put(5);

hashSet.put(3);

//Output: 5,3

5-Object remove(Object key)

Removes the key and its value. Returns the value associated with the key. If the key
is not in the hash table, a null object is returned.
Code Example

HashSet hashSet = new HashSet();

hashSet.put(5);

hashSet.put(3);

hashSet.remove(3);

//Output: 5

4-LINKED LIST
4.1-What is Linked List in Data Structure?

A linked list is a linear data structure, in which the elements are not stored at
contiguous memory locations. The elements in a linked list are linked using pointers
as shown in the below image:

Code Example

class LinkedList {
Node head; // head of list

/* Linked list Node*/


class Node {
int data;
Node next;

// Constructor to create a new node


// Next is by default initialized
// as null
Node(int d) { data = d; }
}
}
4.1.1-What is Insertion?

In this article, insertion in the list is done at the end, that is the new node is
added after the last node of the given Linked List. For example, if the given Linked
List is 5->10->15->20->25 and 30 is to be inserted, then the Linked List becomes 5-
>10->15->20->25->30.
Since a Linked List is typically represented by the head pointer of it, it is required to
traverse the list till the last node and then change the next of last node to new node.

Code Example

public static LinkedList insert(LinkedList list, int data)


{
// Create a new node with given data
Node new_node = new Node(data);
new_node.next = null;

// If the Linked List is empty,


// then make the new node as head
if (list.head == null) {
list.head = new_node;
}
else {
// Else traverse till the last node
// and insert the new_node there
Node last = list.head;
while (last.next != null) {
last = last.next;
}

// Insert the new_node at last node


last.next = new_node;
}

Output:
LinkedList: 1 2 3 4 5 6 7 8

4.1.2-What is Traverles in LinkedList ?

For traversal, below is a general purpose function printList() that prints any
given list by traversing the list from head node to the last.

Code Example

public static void printList(LinkedList list)


{
// Create a node keep the head value.
Node currNode = list.head;

System.out.print("LinkedList: ");

// Traverse through the LinkedList


while (currNode != null) {
// Print the data at current node
System.out.print(currNode.data + " ");

// Go to next node
currNode = currNode.next;
}
}

4.1.3-Delete Method For LinkedList

How to do it:
To delete a node from linked list, do following steps.
1. Search the key for its first occurrence in the list
2. Now, Any of the 3 conditions can be there:

Case 1: The key is found at head


1. In this case, Change the head of the node to the next node of current
head.
2. Free the memory of replaced head node.
Case 2: The key is found at in the middle or last, except at head
3. In this case, Find previous node of the node to be deleted.
4. Change the next of previous node to the next node of current node.
5. Free the memory of replaced node.
Case 3: The key is not found in the list
6. In this case, No operation needs to be done.
Code Example With Steps

public static LinkedList deleteByKey(LinkedList list, int key)


{
// Store head node
Node currNode = list.head, prev = null;

// CASE 1:
// If head node itself holds the key to be deleted

if (currNode != null && currNode.data == key) {


list.head = currNode.next; // Changed head

// Display the message


System.out.println(key + " found and deleted");

// Return the updated List


return list;
}

//
// CASE 2:
// If the key is somewhere other than at head
//

// Search for the key to be deleted,


// keep track of the previous node
// as it is needed to change currNode.next
while (currNode != null && currNode.data != key) {
// If currNode does not hold key
// continue to next node
prev = currNode;
currNode = currNode.next;
}

// If the key was present, it should be at currNode


// Therefore the currNode shall not be null
if (currNode != null) {
// Since the key is at currNode
// Unlink currNode from linked list
prev.next = currNode.next;

// Display the message


System.out.println(key + " found and deleted");
}

// CASE 3: The key is not present


// If key was not present in linked list
// currNode should be null
if (currNode == null) {
// Display the message
System.out.println(key + " not found");
}
// return the List
return list;
}

Output:

LinkedList: 1 2 3 4 5 6 7 8
1 found and deleted
LinkedList: 2 3 4 5 6 7 8
4 found and deleted
LinkedList: 2 3 5 6 7 8
10 not found
LinkedList: 2 3 5 6 7 8

5-DYNAMIC ARRAY

5.1-What is Dynamic Array? And How Do Dynamic Arrays Work?

A Dynamic array(vector in C++, ArrayList in Java) automatically grows when


we try to make an insertion and there is no more space left for the new item. Usually
the area doubles in size.
A simple dynamic array can be constructed by allocating an array of fixed-size,
typically larger than the number of elements immediately required. The elements of
the dynamic array are stored contiguously at the start of the underlying array, and the
remaining positions towards the end of the underlying array are reserved, or unused.
Elements can be added at the end of a dynamic array in constant time by using the
reserved space, until this space is completely consumed.
When all space is consumed, and an additional element is to be added, the
underlying fixed-sized array needs to be increased in size. Typically resizing is
expensive because you have to allocate a bigger array and copy over all of the
elements from the array you have overgrow before we can finally append our item.
Approach: When we enter an element in array but array is full then you create a
function, this function creates a new array double size or as you wish and copy all
element from previous array to new array and return this new array. also we can
reduce size of array. and add element at given position, remove element at the end
default and at position also.

5.1.1-Add Method in Dynamic Array

Add Element: Add element at the end if array size is not enough then then extend
size of array and add element at the end of original array as well as given index.
Doing all that copying takes O(n) time, where n is the number of elements in our
array. That’s an expensive cost for an append. In a fixed-length array, appends only
take O(1) time.

But appends take O(n) time only when we insert into a full array. And that is pretty
rare, especially if we double the size of the array every time we run out of space. So
in most cases appending is still O(1) time, and sometimes it’s O(n) time.

Code Example
public void add(int data)
{
// check no of element is equql to size of array
if (count == size) {
growSize(); // make array size double
} // insert element at end of array
array[count] = data;
count++; }

5.1.2-Delete Method in Dynamic Array

Delete an element from array, default remove() method delete an element


from end, simply store zero at last index and you also delete element at specific
index by calling removeAt(i) method where i is index. removeAt(i) method shift all
right element in left side from given index.

5.1.3-Resize of Array Size

When array has null/zero data(exclude add by you) at the right side of array
whose take unrequited memory, the method srinkSize() free extra memory. When all
space is consumed, and an additional element is to be added, then the underlying
fixed size array need to be increase size. Typically resizing is expensive because you
have to allocate a bigger array and copy over all of the elements from the array you
have overgrow before we can finally append our item.
Code Example

// function makes size double of array


public void growSize()
{

int temp[] = null;


if (count == size) {

// temp is a double size array of array


// and store array elements
temp = new int[size * 2];
{
for (int i = 0; i < size; i++) {
// copy all array value into temp
temp[i] = array[i];
}
}
}

// double size array temp initialize


// into variable array again
array = temp;

// and make size is double also of array


size = size * 2;
}
6-ARRAY

6.1-What is Java Array?

Normally, an array is a collection of similar type of elements that have a


contiguous memory location.

Java array is an object which contains elements of a similar data type. It is a data
structure where we store similar elements. We can store only a fixed set of elements
in a Java array.

Array in java is index-based, the first element of the array is stored at the 0 index.

Code Example

class TestArray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;

// Traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

6.1.1-Advantages

Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.

Random access: We can get any data located at an index position.


6.1.2-Disadvantages

Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used in
Java which grows automatically.

Das könnte Ihnen auch gefallen