0% found this document useful (0 votes)
10 views19 pages

DS Notes by Abhi

Data structure notes for service based MNCs

Uploaded by

romiyorajput18
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)
10 views19 pages

DS Notes by Abhi

Data structure notes for service based MNCs

Uploaded by

romiyorajput18
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/ 19

Examples are in JAVA Programming language.

CONTENTS
LINEAR LIST(DS) ->
ARRAY
STACK
QUEUE
LINKED LIST
SEARCHING
LINEAR
BINARY
SORTING
BUBBLE SORT
INSERTION SORT
SELECTION SORT
NON-LINEAR LIST(DS)->
TREE
GRAPH
DATA STRUCTURES (DS) IN JAVA
Data Structure is a way of organizing all data items that considers not only the elements stored but also their
relationship to each other.

1. LINEAR LIST(DS) -> ARRAY, STACK, QUEUE, LINKED LIST


2. NON-LINEAR LIST(DS)-> TREE, GRAPH

ARRAY

Array: An array is a fixed-size sequenced collection of elements of the same data type.

most commonly 0 based, index.

#### What you need to know:

- Optimal for indexing; bad at searching, inserting, and deleting (except at the end).
- **Linear arrays**, or one dimensional arrays, are the most basic.
- Are static in size, meaning that they are declared with a fixed size.
- **Dynamic arrays** are like one dimensional arrays, but have reserved space for additional elements.
- If a dynamic array is full, it copies its contents to a larger array.
- **Multi dimensional arrays** nested arrays that allow for multiple dimensions such as an array of arrays
providing a 2 dimensional spacial representation via x, y coordinates.
#### Time Complexity:
- Indexing: Linear array: O(1), Dynamic array: O(1)
- Search: Linear array: O(n), Dynamic array: O(n)
- Optimized Search: Linear array: O(log n), Dynamic array: O(log n)
- Insertion: Linear array: n/a Dynamic array: O(n)
Example

public static void main(String[] args) {


int aman[]=new int[5]; //Array Declaration int aman[]={1,2,3,4,5}; 2nd way of declaration
aman[0]= 1;
aman[1]= 2;
aman[2]= 3;
aman[3]= 4;
aman[4]= 5;
for (int i: aman) { // Using for each Loop
System.out.println(i+" Data in array");
}
}
STACK

A Linear list which allows insertion and deletion of an element at one end only is called stack.
 The insertion operation is called as PUSH and deletion operation as POP.

Time Complexity- O(1)

LIFO Data Structure

Functions Are – PUSH , POP ,PEEK, DISPLAY

Example

package MyList; // Package Name


//last in First out

public class MyStack {


int capacity; // capacity of array
int top;
static int[] mystack; //returns something (to be shared everywhere - static)

public MyStack(){ //constructor for initialization

capacity=10;
top=-1;
mystack=new int[capacity]; // Array
}
public boolean isEmpty()
{
return top==-1;
}
public boolean isFull()
{
return top==capacity-1;
}
public int pop() //int is used for return
{
if(isEmpty())
{
System.out.println("Stack is Empty");
}
return mystack[top--];
}

public int push(int x){


if(isFull())
{
System.out.println("Stack is Full");
}
return mystack[++top]=x;
}
public int peek()
{
return mystack[top];
}
public static void display()
{
for (int i:mystack) {
System.out.println(i);

}
}
public static void main(String[] args) {
MyStack mt=new MyStack();
mt.push(34);
mt.push(21);
mt.push(3);
mt.push(4);
System.out.println(mt.peek());
MyStack.display();
}
}
STACK USING LINKEDLIST

package MyList;
public class StackLinkedList {
private ListNode top;
public int length;
public static class ListNode{
int data;
ListNode next;
ListNode(int data){
this.data=data;
this.next=null;
}
}
public StackLinkedList(){
top=null;
length=0;
}
public void push(int x){
ListNode temp=new ListNode(x);
temp.next=top;
top=temp;
length++;
}
public int pop(){
int result=top.data;
if (top.next == null){
System.out.println("List is empty");
}
top=top.next;
length--;
// System.out.println(result);
return result;
}
public void peek(){
ListNode temp=top;
while(temp.next!=null){
System.out.println(temp.data+" <--Stack");
temp=temp.next;
}
System.out.println(temp.data+"<lastStack");
}
public static void main(String[] args) {
StackLinkedList sll=new StackLinkedList();
sll.push(2);
sll.push(3);
sll.push(4);
sll.peek();
sll.pop();
sll.peek();
}
}
QUEUE

(i) Queue (ii) Circular Queue (iii) DQUEUE (iv) Priority Queue

QUEUE

A linear list which allows deletion to be performed at one end of the list and insertion at the other
end is called queue. FIFO (first in first out), Time Complexity- O(1)

package MyList;

public class myQueue {


int rear;
int front;
int capacity;
static int []myqueue;
myQueue() //constructor
{
rear=-1; //insertion
front=-1; //deletion
capacity=5;
myqueue=new int[capacity];
}
boolean isEmpty()
{
return front==rear;
}
public int dequeue() //for removing element
{
if(isEmpty())
{
System.out.println("Queue is empty brother");
}
if(rear>=front)
{
return myqueue[++front];
}
return(Integer) null;
}
public int enqueue(int x) // for addition of elements
{
return myqueue[++rear]=x;
}
public static void display()
{
for (int i :myqueue) {
System.out.println(i);

}
}
public static void main(String[] args) {
myQueue mq= new myQueue();
mq.enqueue(40);
mq.enqueue(30);
System.out.println(mq.dequeue());
System.out.println(mq.dequeue());
System.out.println(mq.dequeue());
mq.display();
}
}

o Front is the end of queue from that deletion is to be performed.


o Rear is the end of queue at which new element is to be inserted.
o The process to add an element into queue is called Enqueue
o The process of removal of an element from queue is called Dequeue.

QUEUE USING LINKEDLIST

package MyList;
import java.util.NoSuchElementException;
//First in first out
//front----->node------>node------rear(insertion)
//enqueue - insertion
//deletion - deletion
public class QueueuLinkedList {
private node front; //remove
private node rear; //insert
private int length;
public QueueuLinkedList (){
front=null;
rear=null;
length=0;
}
private class node{
int data;
node next;
public node(int data){
this.data=data;
this.next=null;
}
}
public int length(){
return length;
}
// public boolean isempty(){
// return length==0;
// }

public boolean isempty() {


return length == 0;
}

// public void insertrear(int data){


// node temp= new node(data);
// if (isempty()){
// front = temp;
// }
// else
// {
// rear.next=temp;
// }
// rear=temp;
// length++;
// }
public void insertrear(int data) {
node temp = new node(data);
if(isempty()) {
front = temp;
} else {
rear.next = temp;
}

rear = temp;
length++;
}

// public void display(){


// if (isempty()){
// return;
// }
// node temp=front;
// while(temp!=null){
// System.out.println(temp.data+" <--Queue");
// temp=temp.next;
// }
// System.out.println("null");
// }
public void print() {
if (isempty()) {
return;
}

node current = front;


while (current != null) {
System.out.print(current.data + " --> ");
current = current.next;
}
System.out.println("null");
}
public int deletefront(){
if (isempty()) {
throw new NoSuchElementException();
}
int result=front.data;
front=front.next;
if (front==null){
rear = null;
}
length--;
return result;

public static void main(String[] args) {


QueueuLinkedList qll= new QueueuLinkedList();
qll.insertrear(31);
qll.insertrear(32);
qll.insertrear(41);
qll.print();
}
}
Circular Queue

o Circular queue is a linear data structure. It follows FIFO principle.


o In circular queue the last node is connected back to the first node to make a circle.
o Elements are added at the rear end and the elements are deleted at front end of the queue.
o Both the front and the rear pointers points to the beginning of the array. It is also called as “Ring buffer”.

DQUEUE

o A dequeue (double ended queue ) is a linear list in which insertion and deletion are performed from
the either end of the structure.
o There are two variations of Dqueue
 Input restricted dqueue- allows insertion at only one end
 Output restricted dqueue- allows deletion from only one end

Priority Queue

A queue in which we are able to insert remove items from any position based on some property
(such as priority of the task to be processed) is often referred as priority queue.

LINKED LIST- SINGLY, DOUBLY, CIRCULAR

• A linked list is a collection of objects stored in a list form.


• A linked list is a sequence of items (objects) where every item is linked to the next.
• Elements of linked list are called nodes where each node contains two things, data and pointer to next
node.
• Linked list require more memory compared to array because along with value it stores pointer to next
node.
• Linked lists are among the simplest and most common data structures. They can be used to implement
other data structures like stacks, queues, and symbolic expressions, etc.

Operations on linked list

• Insert
o Insert at first position
o Insert at last position
o Insert into ordered list
• Delete
• Traverse list (Print list)
• Copy linked list

Types of linked list


Singly Linked List
• It is basic type of linked list.
• Each node contains data and pointer to next node.
• Last node’s pointer is null.
• Limitation of singly linked list is we can traverse only in one direction, forward direction.

EXAMPLE

package MyList;
// SinglyLinkedList creating node ,display, size, insertion at begining ,at end,any pos
// deleteFirst,deleteLast ,deleteAnyPos ,Searching,reversing Linkedlist
public class SinglyLinkedList {
public static Node head; //creating head node
public static class Node //class node
{
int data;
Node next;
Node(int data){ //constructor
this.data=data;
this.next=null;
}
}
public void display(Node head) { //display
Node current = SinglyLinkedList.head;
while(current!=null){
System.out.println(current.data+" ");
current=current.next;
}
// System.out.println("null");
}
public void size() //size
{
if(head==null){
System.out.println("List is empty");
}
int count=0;
Node current = head;
while (current!=null)
{
count++;
current=current.next;
}
System.out.println(count+" ");
}
public void insertionAtBegining(int val){ //inserting at first position
Node newNode= new Node(val);
newNode.next=head;
head=newNode;
}
public void insertionAtEnd(int val){
Node neWNode = new Node(val);
if(head==null){
head=neWNode;
return;
}
Node current =head;
while (null!=current.next){
current=current.next;
}
current.next=neWNode;
}
public void insertionAtAnyposition(int d,int position){
Node node = new Node(d);
if(position==1)
{
node.next=head;
head=node;
}
else {
Node previous = head;
int count=1;
while(count < position - 1)
{
previous=previous.next;
count++;
}
Node current=previous.next;
previous.next=node;
node.next=current;
}
}
public Node deleteFirst(){
if(head==null){
return null;
}
Node temp =head;
head= head.next;
temp.next=null;
return temp;
}
public Node deleteLast(){
if (head==null || head.next==null){
return null;
}
Node current = head;
Node previos= null;
while (current.next!=null){
previos=current;
current=current.next;
}
previos.next=null;
return current;
}
public void deleteAtAnypos(int position) {

if (position == 1) {
head = head.next;
} else {
Node previous = head;
int count = 1;
while (count < position - 1) {
previous = previous.next;
count++;
}
Node current = previous.next;
previous.next=current.next;
}
}
public boolean Search(Node head, int searchkey) {
if(head==null){
return false;
}
Node current = head;
while (current != null) {
if(current.data == searchkey)
{
return true;
} current=current.next;
} return false;
}
public Node reverse(Node head){
if(head==null){
return head;
}
Node current=head;
Node previous =null;
Node next =null;
while (current!=null){
next=current.next;
current.next=previous;
previous=current;
current=next;
}
return previous;
}

public static void main(String[] args) {


SinglyLinkedList first=new SinglyLinkedList(); //object of class SinglyLinkedList
first.head= new Node(21); //object of class node
Node second=new Node(31);
Node third = new Node(41);
Node fourth = new Node(51);
first.head.next=second; //adding pointers of node
second.next=third;
third.next=fourth;
fourth.next=null;
// first.insertionAtBegining(21);
// first.insertionAtBegining(41);
// first.insertionAtBegining(61);
// first.display();
// first.insertionAtEnd(21);
// first.insertionAtEnd(41);
// first.insertionAtEnd(61);
// first.insertionAtAnyposition(3,2);

// System.out.println(first.deleteFirst().data+" <---- deleted");


// if(first.Search(head,1)){
// System.out.println("Search key found");
// }else
// {
// System.out.println("Sorry!not found");
// }
// first.display();
// first.size();
SinglyLinkedList sll=new SinglyLinkedList();
// sll.insertionAtEnd(21);
// sll.insertionAtEnd(31);
// sll.insertionAtEnd(41);
sll.display(head);
Node reverseList= sll.reverse(head);
System.out.println("After reversing");
sll.display(reverseList);

}
}

CIRCULAR Linked List

• Circular linked list is a singly linked list where last node points to first node in the list.
• It does not contain null pointers like singly linked list.
• We can traverse only in one direction that is forward direction.
• It has the biggest advantage of time saving when we want to go from last node to first node, it
directly points to first node.
• A good example of an application where circular linked list should be used is a timesharing problem
solved by the operating system.

EXAMPLE

package MyList;

import java.util.NoSuchElementException;

public class CircularLinkedList {


public ListNode last;
public int length;
public class ListNode{
int data;
ListNode next;
public ListNode(int data){
this.data=data;
}
}
public CircularLinkedList(){
this.last=null;
this.length=0;
}
public boolean isEmpty(){
return last==null;
}
public void insertAtBegin(int val){
ListNode newnode= new ListNode(val);
if (isEmpty()){
last=newnode;
}else
{
newnode.next= last.next;
}
last.next=newnode;
length++;
}
// inserAtEnd
public void insertAtEnd(int val) {
ListNode newnode = new ListNode(val);
if (isEmpty()){
last=newnode;
newnode.next=newnode;
}
newnode.next=last.next;
last.next=newnode;
last=newnode;
}
// removefirst();
public ListNode removeFirst(){
if (isEmpty()){
throw new NoSuchElementException();
}
ListNode newnode=last.next;
if (last.next==last){
last=null;
}else{
last.next=newnode.next;
}
newnode.next=null;
length--;
return newnode;
}
//print
public void print(){
if (isEmpty()){
return;
}
ListNode first=last.next;
while (first!=last){
System.out.println(first.data+"<---node");
first=first.next;
}
System.out.println(first.data+"<---last node");
}
public static void main(String[] args) {
CircularLinkedList cl=new CircularLinkedList();
// cl.insertAtBegin(1);

cl.insertAtEnd(41);
cl.insertAtEnd(24);
cl.insertAtEnd(31);
cl.print();
System.out.println(cl.removeFirst().data+"<--41 will be removed");

cl.insertAtBegin(31);
cl.insertAtBegin(21);
cl.print();
}
}

DOUBLY Linked list


• Each node of doubly linked list contains data and two pointers to point previous (LPTR) and next
(RPTR) node.

• Main advantage of doubly linked list is we can traverse in any direction, forward or reverse.
• Other advantage of doubly linked list is we can delete a node with little trouble, since we have
pointers to the previous and next nodes. A node on a singly linked list cannot be removed unless we
have the pointer to its predecessor.
• Drawback of doubly linked list is it requires more memory compared to singly linked list because we
need an extra pointer to point previous node.
• L and R in image denote left most and right most nodes in the list.
• Left link of L node and right link of R node is NULL, indicating the end of list for each direction.

EXAMPLE

package MyList;
import java.util.NoSuchElementException;
//creating DoublyLinked list / insertionATBEgin
public class DoublyLinkedList {
ListNode head;
ListNode tail;
int length;

public class ListNode{


int data;
ListNode next;
ListNode previous;
public ListNode(int data){
this.data=data;
}
}
public DoublyLinkedList(){
this.head=null;
this.tail=null;
this.length=0;
}
public boolean isEmpty()
{
return head==null;
}
public int length(){
return length;
}
// Display
public void Display(){
if (head==null || tail==null){
return;
}
// ListNode temp1= tail;
ListNode temp= head;
while (temp!=null){
System.out.println(temp.data+"<----Node");
temp=temp.next;
}
// System.out.println(temp1.data+"<-- Node");
}
// Insertion At begining
public void insertionATBEgin(int val)
{
ListNode Node= new ListNode(val);
if (isEmpty()){
tail=Node;
}else {
head.previous=Node;
}
Node.next=head;
head=Node;
}
public void insertAtEnd(int val){
ListNode Node = new ListNode(val);
if (isEmpty()){
head=Node;
}else{
tail.next=Node;
Node.previous=tail;
}
tail=Node;
}
//insertAtAnyPos
public void insertAtAnyPos(int val,int position){ // code by me
ListNode Node=new ListNode(val);
if (isEmpty()){
tail=Node;
}else {
ListNode current = head;
int count = 1;
while (count < position - 1) {
current = current.next;
count++;
}
ListNode new1 = current.next;
current.next = Node;
Node.previous = current;
Node.next = new1;
}
}
//deleteFirst
public ListNode deleteFirst(){
if (isEmpty()){
throw new NoSuchElementException();
}
ListNode temp=head;
if (head==tail){
tail=null;
}else
{
head.next.previous=null;
}
head=head.next;
temp.next=null;
return temp;
}
// Deletelast
public ListNode Deletelast(){
if (isEmpty()){
throw new NoSuchElementException();
}
ListNode temp=tail;
if (head==tail){
tail=null;
}else
{
tail.previous.next=null;
tail.previous=tail;
}
temp.previous=null;
return tail;
}
public static void main(String[] args) {
DoublyLinkedList dl=new DoublyLinkedList();
// dl.insertionATBEgin(21);
// dl.insertionATBEgin(31);
// dl.insertionATBEgin(41);
dl.insertAtEnd(21);
dl.insertAtEnd(31);
dl.insertAtEnd(51);
// dl.insertAtAnyPos(21,1);
System.out.println(dl.Deletelast().data+"<-deleted data");
dl.Display();
}
}

SEARCHING
SEARCHING

Linear/Sequential Search

 In computer science, linear search or sequential search is a method for finding a particular value in a list that
consists of checking every one of its elements, one at a time and in sequence, until the desired one is found.
 It is a special case of brute-force search. Its worst case cost is proportional to the number of elements in the
list.

package Searching;

public class LinearSearch {


public void Search(int arr[],int search){
int s=search;
int l= arr.length;
for (int i=0;i<l;i++){
if (arr[i]==s){
System.out.println(i);
}
}
}
public static void main(String[] args) {
int arr[]={2,3,4,1,5,6,7};
LinearSearch ls=new LinearSearch();
ls.Search(arr,1);
}
}

Binary Search

 If we have an array that is sorted, we can use a much more efficient algorithm called a Binary Search.
 In binary search each time we divide array into two equal half and compare middle element with search
element.
 If middle element is equal to search element then we got that element and return that index otherwise if
middle element is less than search element we look right part of array and if middle element is greater than
search element we look left part of array.

package Searching;

public class BinarySearch {


public int binarySearch(int[]arr ,int key){
int low =0;
int high=arr.length-1;
while (low<=high){
int mid=(high+low)/2;
if (arr[mid]==key)
{
return mid;
}
if (key<arr[mid]){
high=mid-1;
}else
{
low=mid+1;
}
}
return -1;
}
public static void main(String[] args) {
int []arr={11,22,33,44,55,66,77,88,99};
BinarySearch bs=new BinarySearch();
System.out.println(bs.binarySearch(arr,77));
}
}

SORTING
BUBBLE SORT (Sinking Sort)

 It is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of
adjacent items and swapping them if they are in the wrong order.
 The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
 The algorithm gets its name from the way smaller elements "bubble" to the top of the list.
 As it only uses comparisons to operate on elements, it is a comparison sort.
EXAMPLE

package Sorting;

public class BubbleSort {


public static void main(String[] args) {
int[] arr ={2,3,6,5,4,1};
int l = arr.length;
for (int i=0;i<l-1-i;i++){
for (int j=0;j<l-1;j++){
if (arr[j+1]<arr[j]){
int temp =arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for (int BubbleSorted: arr) {
System.out.println(BubbleSorted+" ");

}
}
}

SELECTION SORT

Array is imaginary divided into two parts - sorted one and unsorted one.
 At the beginning, sorted part is empty, while unsorted one contains whole array.
 At every step, algorithm finds minimal element in the unsorted part and adds it to the end of the sorted one.
 When unsorted part becomes empty, algorithm stops.

EXAMPLE

package Sorting;
//put smallest value in first place
// the value which was at first place put in the place of smallest value
public class SelectionSorting {
public static void main(String[] args) {
int[] arr ={5,1,10,2,9};
int l = arr.length;
for (int i=0;i<l-1;i++){
int min=i;
for (int j=i+1;j<l;j++){
if (arr[j]<arr[min]){
min=j;
}
}
int temp=arr[min];
arr[min]=arr[i];
arr[i]=temp;
}
for (int k : arr) {
System.out.println(k+" ");
}

}
}
INSERTION SORT

At the beginning, just put the smallest element in the 0th index of array and shift the 0th element to the 1st index.

Now 0th index is sorted, put the smallest element at the 1st index of array and shift the 1st element to the 2nd
index. Do this till the array is sorted.

EXAMPLE

package Sorting;
//just put smalller in first place and shift

import java.security.AlgorithmConstraints;

public class InsertionSort {


public static void main(String[] args) {
int[] arr ={3,2,6,5,4,1};
int l = arr.length;
// Algorithm
for (int i=1;i<l;i++){
int temp =arr[i];
int j=i-1;
while (j>=0 && arr[j]>temp){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=temp;
}
// Algorithm
for (int k : arr) {
System.out.println(k+" ");
}
}
}

You might also like