Skip to main content

LinkedList Interview Questions


1) Print Elements of Linked List

class Node {
int data;
Node nextNode;
}
/**
* This method prints all the Nodes/Values of the
* LinkedList
*
*/
public void printNodes() {
Node currentNode = headNode;
if(currentNode==null) {
System.out.println(" The Node is Null");
return;
} else {
System.out.print(" "+ currentNode.getData());
while(currentNode.getNextNode()!=null) {
currentNode = currentNode.getNextNode();
System.out.print("=> "+ currentNode.getData());
}
}
}

2) Reverse LinkedList



3) Delete a given Element of a LinkedList



4) Delete kth Element from headNode of  a LinkedList



5) Delete kth Element from tailNode of  a LinkedList



6) Detect if a LinkedList contains a Cycle



7) Remove an Element from a DoublyLinkedList



8) Merge Elements of a DoublyLinkedList



9) Create a Cache such that the Elements can be added at Head and removed from Tail, in O(1)



10) Merge K Sorted Lists

K Sorted Linked Lists cab be merged using MinHeap. All the elements from all the K Linked Lists are added to the MinHeap one by one. Create a Dummy LinkedList Node and add all the nodes from the Min Heap to the LinkedList node. Return the Next Node of the dummy Node which becomes the head for the combined LinkedList.


/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for(ListNode listNode : lists) {
ListNode pointer = listNode;
while(pointer!=null) {
minHeap.add(pointer.val);
pointer = pointer.next;
}
}
ListNode dummy = new ListNode(0);
ListNode temp = dummy;
while(!minHeap.isEmpty()) {
temp.next = new ListNode(minHeap.remove());
temp = temp.next;
}
return dummy.next;
}
}

Comments

Popular posts from this blog

Running Multiple Operating Systems(Windows and Ubuntu Linux) on the same machine

VMWare Player is a freely downloadable VMWare. Download VMWare player software and install it on your windows OS download an image of the Ubuntu Linux Desktop version called Ubuntu from http://www.ubuntu.com/getubuntu/download that in iso image format. Then download VMWare configuration bundle that contains a list of files, extract those file to some folder like C:\OS\. Then edit the file" os.vmx file and give the path of the .iso image in that file in the line like below. ide1:0.fileName = C:\OS\ubuntu-8.10-desktop-i386.iso" Now open the file os.vmx file using the vmware player, that will open the Ubuntu OS. You will get a list of options in that select the option install Ubuntu without changing your current configuration of the system Now that will start the Ubuntu OS in a window inside your windows OS. Now you have a browser and all the applications inside the Ubuntu OS, you can start working on that. Double click on this window/expand it to show in full screen. To switch ...