Showing posts with label Linked List. Show all posts
Showing posts with label Linked List. Show all posts

Wednesday, April 20, 2016

Amazon Question: Print Last N nodes of Linked List in reverse

Given a singly linked list's head and an integer N, print last N nodes of the list in reverse order.
Example:
List = 1->2->3->4->5->6->7->8
N = 3
Output = 8, 7, 6,

    public void printRev(int count)    { // count = N
        temp = count;

// this here is the head node
        System.out.println(printRev(this, new StringBuffer()));
    }
    private int temp;
    private String printRev(LinkedList L, StringBuffer sb)    {
        if(L.next!=null)
            printRev(L.next, sb);
        if(temp>0)    {
            sb.append(L.data).append(", ");
            temp--;
        }
        return sb.toString();
    }

Saturday, December 19, 2015

Reversing Parts of a LinkedList

Initial LinkedList: 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 

Input: count = 3
Output: 3, 2, 1, 6, 5, 4, 9, 8, 7, 0, 

Input: count = 4
Output: 4, 3, 2, 1, 8, 7, 6, 5, 0, 9,

Input: count = 7
Output: 7, 6, 5, 4, 3, 2, 1, 0, 9, 8,


    public void compute(int count)    {
        LinkedList L = this;
        int i=0;
        StringBuffer sb = new StringBuffer();
        Stack<Integer> S = new Stack<Integer>();
        while(L!=null)    {
            if(i<count)    {
                S.push(L.data);
                L=L.next;
                i++;
            }    else    {
                while(!S.isEmpty())
                    sb.append(S.pop()).append(", ");
                i=0;
            }
        }
        while(!S.isEmpty())
            sb.append(S.pop()).append(", ");
        System.out.println(sb.toString());
    }

Inserting an Array of Elements in a Linked List

    public void insert(int... data)    {
        LinkedList L = this;
        while(L.next!=null)    {
            L=L.next;
        }
        int size=data.length;
        for(int i=0; i<size; i++)    {
            L.next=new LinkedList(data[i]);
            L=L.next;
        }
    }

Saturday, November 28, 2015

Create and Detect Loop in Linked List

The Linked List program is available here: link

     public boolean isLoopExist()    {
        LinkedList L = this;
        LinkedList slow = L;
        LinkedList fast = L;
        boolean isLoop = false;
        while(fast.next!=null)    {
            slow=slow.next;
            fast=fast.next.next;
            if(slow==fast)    {
                isLoop = true;
                break;
            }
        }
        return isLoop;
    }
    public void createLoop(int index)    {
        LinkedList L = this;
        for(int i=2; i<index; i++)    {
            L=L.next;
        }
        LinkedList indexPrevNode = L;
        while(L.next!=null)    {
            L=L.next;
        }
        L.next=indexPrevNode.next;
    }

Stack Implementation using Linked List

This is a Stack Implementation using LinkedList in Java. As in Java we don't have pointers and hard to remove head node in a empty list, we are using a dummy head node.

public class Stack {
    Stack next;
    int data;
    private int size;
    public Stack() {
        this.size=-1;
        this.data=-999; //Garbage Value to denote Head
        this.next=null;
    }
    public Stack(int data) {
        this.data=data;
        this.next=null;
    }
    public void push(int... data)    {
        int s = data.length;
        for(int i=0; i<s; i++)
            push(data[i]);
    }
    public void push(int data)    {
        Stack S = this;
        if(size==-1)    {
            S.next=new Stack(data);
        }    else    {
            Stack newNode = new Stack(data);
            newNode.next=S.next; //Head is a dummy node here
            S.next=newNode;
        }
        size++;
    }
    public final static int ErrorCode = -999;
    public int pop()    {
        Stack S = this;
        if(size>-1)    {
            int value = S.next.data;
            S.next=S.next.next;
            size--;
            return value;
        }    else    {
            System.out.println("Error: Stack is Empty");
            return ErrorCode;
        }
    }
    public int size()    {
        return size;
    }
    public int peek()    {
        Stack S = this;
        if(size>-1)    {
            return S.next.data;
        }    else    {
            System.out.println("Error: Stack is Empty");
            return ErrorCode;
        }
    }
    public void printStack()    {
        Stack S = this;
        S=S.next; // first node is dummy
        StringBuffer sb = new StringBuffer();
        while(S!=null)    {
            sb.append(S.data).append(", ");
            S=S.next;
        }
        System.out.println(sb.toString());
    }
}

Thursday, November 26, 2015

LinkedList print kth to last element

This module returns kth to last element of a Linked List

    public String kthLastElement(int k)    {
        LinkedList L = this;
        for(int i=1; i<k; i++)    {
            L=L.next;
        }
        StringBuffer sb = new StringBuffer();
        while(L!=null)    {
            sb.append(L.data).append(", ");
            L=L.next;
        }
        return sb.toString();
    }

Check if a LinkedList is a Palindrome

Input:
LinkedList L = new LinkedList("HeleH");
L.printList();
System.out.println(L.isPalindrome());

Program:
import java.util.Stack;

public class LinkedList {
    int data;
    LinkedList next;
    private LinkedList(int data) {
        this.data=data;
        this.next=null;
    }
    public LinkedList(String data) {
        char[] a = data.toCharArray();
        int size=a.length;
        if(size>0)    {
            this.data=a[0];
            this.next=null;
            for(int i=1; i<size; i++)
                append(a[i]);
        }
    }
    public boolean isPalindrome()    {
        LinkedList L = this;
        Stack<Integer> S=new Stack<Integer>();
        LinkedList slow = L;
        LinkedList fast = L;
        while(fast!=null && fast.next!=null)    {
            S.push(slow.data);
            fast = fast.next.next;
            slow = slow.next;
        }
        boolean flag = true;
        if(fast!=null) //String has odd number of char
            slow = slow.next;
        while(slow!=null)    {
            if(slow.data!=S.pop())    {
                flag=false;
                break;
            }
            slow = slow.next;
        }
        return flag;
    }
    public void append(int data)    {
        LinkedList L = this;
        while(L.next!=null)
            L=L.next;
        L.next=new LinkedList(data);
    }
    public void printList()    {
        LinkedList L = this;
        StringBuffer sb = new StringBuffer();
        while(L!=null)    {
            sb.append((char)L.data);
            L=L.next;
        }
        System.out.println("String: "+sb.toString());
    }
}


This program also shows how to use an integer data linked list to store characters.

Wednesday, November 25, 2015

Reverse a Single Linked List in Java using Recursion

You can refer for Linked List in Java program here: link

This is a program to reverse a linked list using recursion.
    public String reverseList()    {
        return reverseList(this, new StringBuffer()).toString();
    }
    private StringBuffer reverseList(LinkedList L, StringBuffer sb)    {
        if(L!=null)    {
            reverseList(L.next, sb);
            sb.append(L.data).append(", ");
        }
        return sb;
    }

Monday, November 23, 2015

Delete Node if you have access only to that node

The Linked List program is available here: link
    public void deleteNode(LinkedList Node)    {
        if(Node!=null && Node.next!=null)    {
            Node.data=Node.next.data;
            Node.next=Node.next.next;
        }
    }

Kth to Last Element in Linked List

The Linked List program is available here: link
    public String kthLastElement(int k)    {
        LinkedList L = this;
        for(int i=1; i<k; i++)    {
            L=L.next;
        }
        StringBuffer sb = new StringBuffer();
        while(L!=null)    {
            sb.append(L.data).append(", ");
            L=L.next;
        }
        return sb.toString();
    }

Remove Duplicates in Linked List

The Linked List program is available here: link

    public void RemoveDuplicatesWithBuffer()    {
        LinkedList L = this;
        LinkedList previous = null;
        HashSet<Integer> H = new HashSet<>();
        while(L!=null)    {
            if(H.contains(L.data))    {
                previous.next = L.next;
            }    else    {
                H.add(L.data);
                previous=L;
            }
            L=L.next;
        }
    }
    public void RemoveDuplicatesWithoutBuffer()    {
        LinkedList L = this;
        while(L!=null)    {
            LinkedList runner = L;
            while(runner.next!=null)    {
                if(runner.next.data==L.data)
                    runner.next=runner.next.next;
                else               
                    runner=runner.next;
            }
            L=L.next;
        }
    }

Wednesday, November 4, 2015

Linked List Binary Search

 This  is a program to perform Binary Search in a Sorted Linked List

Input: Sorted List of Elements:

    public int Search(int element)    {
        return Search(element, 1, sizeOfList());
    }
   
    private int Search(int element, int StartinDex, int EndInDex) {
        LinkedList L = this;
        int middle = (StartinDex+EndInDex)/2;
        if(L.getValue(middle)==element)    {
            return middle;
        }    else if(L.getValue(middle)<element)    {
            return Search(element, middle+1, EndInDex);
        }    else    {
            return Search(element, StartinDex, middle-1);
        }
    }


 For Linked List Code, look at this link

Tuesday, November 3, 2015

Reverse a Single Linked List in Java

Input: 
LinkedList ll = new LinkedList(0);
ll.append(1);
ll.appendList(2,3,4,5,6,7,8,9);
ll.insertFirst(-1);
ll.insertMiddle(33, 3);
ll.printList();
ll.ReverseList();
ll.printList();
ll.ReverseList();
ll.printList();

 

Program:

public class LinkedList {
    LinkedList next;
    int data;
    private int size;
    public static final int ERROR_CODE = -99999;
    public LinkedList(int data) {
        next = null;
        this.data = data;
        this.size=0;
    }
   
    public int sizeOfList()    {
        return ((this.size)+1);
    }
   
    public void appendList(int... data)    {
        int length = data.length;
        for(int i=0; i<length; i++)
            append(data[i]);
    }
   
    public void append(int data)    {
        LinkedList L = this;
        for(; L.next!=null; L=L.next)    {
        }
        L.next = new LinkedList(data);
        this.size++;
    }
   
    public void printList()    {
        LinkedList L = this;
        StringBuffer sb = new StringBuffer();
        for(; L.next!=null; L=L.next)    {
            sb.append(L.data);
            sb.append(", ");
        }
        sb.append(L.data);
        sb.append(", ");
        System.out.println(sb.toString());
    }
   
    public int removeLast()    {
        LinkedList L = this;
        for(;L.next.next!=null;L=L.next)    {}
        int pop = L.next.data;
        L.next=null;
        this.size--;
        return pop;
    }
   
    public void insertFirst(int data)    {
        LinkedList L = this;
        int headData = L.data;
        LinkedList temp = L.next;
        LinkedList newNode = new LinkedList(headData);
        newNode.next = temp;
        L.data = data;
        L.next = newNode;
        this.size++;
    }
   
    public void Rotate(int times)    {
        for(int i=0;i<times;i++)    {
            insertFirst(removeLast());
        }
        insertFirst(removeLast());
    }
   
    private int removeHead()    {
        LinkedList L = this;
        if(L.next==null)    {
            System.out.println("Single Element List can't be removed");
            return ERROR_CODE;
        }    else    {
            int val = L.data;
            LinkedList temp = L.next.next;
            L.data=L.next.data;
            L.next=temp;
            this.size--;
            return val;
        }
       
    }
   
    public void insertMiddle(int data, int possition)    {
        if(possition==1)    insertFirst(data);
        else if(possition==sizeOfList())    append(data);
        else    {
            LinkedList L = this;
            for(int i=2; i<possition; i++)
                L=L.next;
            LinkedList newNode = new LinkedList(data);
            LinkedList temp = L.next;
            L.next = newNode;
            L.next.next=temp;
            this.size++;
        }
    }
   
    public int remove(int possition)    {
        if(possition==1)    return removeHead();
        else if(possition<=this.size)    {
            LinkedList L = this;
            possition--;
            for(int i=1; i<possition; i++)
                L=L.next;
            int val = L.next.data;
            L.next=L.next.next;
            this.size--;
            return val;
        }    else if(possition==sizeOfList())    {
            return removeLast();
        }
        else    {
            System.out.println("Error, no possition found");
            return ERROR_CODE;
        }
    }
   
    public int Replace(int data, int possition)    {
        LinkedList L = this;
        if(possition>sizeOfList())    {
            return ERROR_CODE;
        }    else if(possition==1)    {
            int val = L.data;
            L.data=data;
            return val;
        }    else    {
            for(int i=2; i<possition; i++)   
                L=L.next;
            int val = L.next.data;
            L.next.data=data;
            return val;
        }
    }
   
    public int getValue(int possition)    {
        LinkedList L = this;
        if(possition>sizeOfList())    {
            return ERROR_CODE;
        }    else if(possition==1)    {
            return L.data;
        }    else    {
            for(int i=2; i<possition; i++)   
                L=L.next;
            return L.next.data;
        }
    }
   
    public void SwapPossitions(int a, int b)    {
        if(a>sizeOfList()||b>sizeOfList())    {
            System.out.println("Error Out of Bound Possition");
        }    else if(a==b)    return;
        else    {
            Replace(Replace(getValue(a), b), a);
        }
    }
   
    public void ReverseList()    {
        int half = sizeOfList()/2;
        for(int i=1; i<half; i++)    {
            SwapPossitions(i, (sizeOfList()-i+1));
        }
    }
}

Wednesday, September 3, 2014

Simple Linked List Using Java

public class List {
List next;
int data;

List(int d) {
data = d;
next = null;
}

void appendData(int d) {
List l = new List(d);
List n = this;
while(n.next != null) {
n = n.next; 
}
n.next = l;
}

void printData() {
List n = this;
for(; n.next != null; n = n.next)
System.out.println(n.data);
System.out.println(n.data);
System.out.println("-END-");
}

void appendMiddle(int d, int position) {
List n = this;
for(int i=1; i<position; i++)
n=n.next;
List l = new List(d);
l.next = n.next;
n.next = l;
}

void deleteEnd() {
List n = this;
for(; n.next.next!=null; n=n.next) {}
n.next = null;
}

void deleteMiddle(int possition) {
List n = this;
for(int i=1; i<possition; i++)
n=n.next;
List a = n.next;
n.next = n.next.next;
a = null;
}
}
UA-39217154-2