Write a java method in your Linked List Project to perform the sorted insertion in your Linked List. Sorted insertion is one in which, whenever you insert a new element, it is inserted on its sorted location. but I'm not getting the output here is my code.
{
public void insertSorted(int data)
{
Node temp = new Node(data);
if(head == null || head.Data > data)
{
temp.next = head;
head = temp;
}
Node head2 = head;
while(head2.next != null && head2.next.Data < data)
{
head2 = head2.next;
}
temp.next = head.next;
head.next = temp;
}
public void Display()
{
Node t = head;
while(t != null)
{
System.out.print(t.Data+" -> ");
t = t.next;
}
System.out.println("NULL");
}
}
You can try this one it will work as you expected ->
public void seprator1(Node curr) {
if (curr == null || curr.next == null) {
return;
}
Node Even, EvenTail, oddStartingNode, oddEndNode;
Even = EvenTail = oddStartingNode = oddEndNode = null;
while (curr != null) {
if (curr.data % 2 == 0) {
if (Even == null) {
Even = curr;
EvenTail = Even;
} else {
EvenTail.next = curr;
EvenTail = EvenTail.next;
}
} else {
if (oddStartingNode == null) {
oddStartingNode = curr;
oddEndNode = oddStartingNode;
} else {
oddEndNode.next = curr;
oddEndNode = oddEndNode.next;
}
}
curr = curr.next;
}
displayNode(Even);
System.out.println();
displayNode(oddStartingNode);
}
private void displayNode(Node node) {
if (node == null) {
return;
}
System.out.print(node.data+" ");
displayNode(node.next);
}
Related
I'm using a generic linked list to implement priority queue where I use the comparable function for the insert function where it finds a slot where it's size is bigger than the current node. I have problem actually getting the add function insert the elements according priority queue requirements. The priority queue should go from smallest to biggest.
Edit: I realize the problem lies with inserting a number bigger than the head. During add 11, the function only compares with 5 and add it after 5 which ruins the sequence.
Current output
PQ: 5
PQ: 5,10
PQ: 5,9,10
PQ: 5,11,9,10
PQ: 5,7,11,9,10
PQ: 2,5,7,11,9,10
Desired output
PQ: 2,5,7,9,10,11
My add function
public class PQLinkedList<T extends Comparable<T>>{
private class Node{
private T data;
private Node next;
// Constructor that takes in data to input for the node
public Node(T data) {
this.data = data;
this.next = null;
}
}
private int length = 0;
private Node head;
int cmp = 0;
public PQLinkedList() {
head = null;
}
//Compare with each element till it finds a suitable position to insert itself
//Ascending order
//INCOMPLETE
//Compare part of this code is not complete!
public void addPQ( T data) {
Node node = new Node(data);
Node temp2 = null;
if ( head == null) {
addFirst(data);
}
else {
Node curr = head;
int count = getSize();
while ( count != 0) {
cmp = data.compareTo(curr.data);
if ( cmp < 0 ) {
addFirst(data);
break;
}
else if (cmp>=0 ){
if ( curr.next == null) {
curr.next = node;
break;
}
// if there curr.next is not empty
// Move all the nodes towards to tail by 1
else {
// after = one space after pos
// PROBLEM
temp2 = curr.next;
Node after = curr.next;
while( after != null) {
after = after.next;
}
node.next = temp2;
curr.next = node;
break;
}
}
else {
curr = curr.next;
}
count--;
}
}
length++;
}
private void addFirst(T data) {
Node node = new Node(data);
if ( head == null ) {
head = node;
}
else {
Node temp = head;
head = node;
node.next = temp;
}
length++;
}
//TO-DO
public void remove( T data) {
if ( !search(data)) {
System.out.println("Linked list does not contain that element!");
return;
}
else if ( head.data == data) {
head = head.next;
}
else {
// If curr is the node to be deleted.
// link from previous node to curr, link from curr to next node
//Traverse through the linkedlist till it finds the node to be deleted and skip it
Node curr = head;
while ( curr != null & curr.next != null ) {
if ( curr.next.data == data) {
//Check if the node 2 next after curr is null
//if so, remove curr.next which contains the value that we want to delete
if ( curr.next.next != null) {
curr.next = curr.next.next;
}
//curr.next.next is null so just curr.next which contains the value we want to delete
else {
curr.next = null;
}
}
//Traverse the curr node
else {
curr = curr.next;
}
}
length--;
}
}
// Retrieves and removes the head of the priority queue
public T poll() {
if ( isEmpty()) {
System.out.println("Linked list is empty!");
return null;
}
else {
Node temp = null;
temp = head ;
head = head.next;
length--;
return temp.data;
}
}
// Retrieves the head of the priority queue
public T peek() {
if ( isEmpty()) {
System.out.println("Linked list is empty!");
return null;
}
else {
return head.data;
}
}
public void clear() {
Node curr = head;
while ( curr != null) {
curr = curr.next;
}
}
public int getSize() {
return length;
}
public boolean search(T data) {
if ( isEmpty()) {
System.out.println("Linked list is empty!");
return false;
}
else {
Node node = head;
while ( node != null ) {
if ( node.data == data) {
return true;
}
node = node.next;
}
return false;
}
}
public boolean isEmpty() {
if ( length == 0) {
return true;
}
return false;
}
#Override
public String toString() {
String str = "PQ: ";
Node node = head;
while ( node != null) {
str = str + node.data;
if ( node.next != null) {
str = str + ",";
}
node = node.next;
}
return str;
}
}
My main
public class priorityQueueImplementation {
public static void main(String[] args) {
PQLinkedList<Integer> test = new PQLinkedList<Integer>();
test.add(5);
test.add(10);
test.add(9);
test.add(11);
test.add(7);
test.add(2);
System.out.println( test.toString());
}
}
Since this is a singly linked list, we cannot add node to previous node. We can only add to subsequent node. During node insertion, we need to compare data with the list. One every node, there are 5 cases:
current is null, data become the new head
data is smaller than current, data become the new head
data is greater than current, data is smaller then next. Insert data between current and next
data is greater than current, next is null. Insert data after current
data is greater than current, data is greater then next. Wait for next iteration
public void addPQ(T data) {
Node node = new Node(data);
Node curr = head;
if (head == null) {
// current is null, data become the new head
addFirst(data);
} else {
while (curr != null) {
int cmpLeft = data.compareTo(curr.data);
if (cmpLeft < 0) {
// data is smaller than current, `data` become the new head
addFirst(data);
break;
} else {
// data is greater than current
if (curr.next == null) {
// next is null. Insert `data` after `current`
addAfter(curr, node);
break;
} else {
int cmpRight = data.compareTo(curr.next.data);
if (cmpRight < 0) {
// data is smaller then next. Insert data between current and next
addAfter(curr, node);
break;
}
}
// data is greater then next. Wait for next iteration
curr = curr.next;
}
}
}
}
private void addAfter(Node currNode, Node newNode) {
if (currNode == null) {
currNode = newNode;
} else {
Node tempTail = currNode.next;
currNode.next = newNode;
newNode.next = tempTail;
}
length++;
}
output
PQ: 2,5,7,9,10,11
I am trying to delete an specific element from the linkedlist, however i am getting null pointer exception. Could any one pls fix my below mentioned code...
public void deleteElement(T num)
{
Node<T> ele = new Node<T>(num);
if(head == null){
System.out.println("Underflow");
return;
}
Node<T> temp = head;
while(temp != null)
{
if(temp.data == num){
temp.previous.next = temp.next;
return;
}
else
temp = temp.next;
}
size--;
}
You should modify inside your while loop like this:
while(temp != null)
{
if(temp.data == num) {
if(temp.previous != null) {
temp.previous.next = temp.next;
}
// you have to link-up the next's previous with temp's previous too
if(temp.next != null) {
temp.next.previous = temp.previous;
}
temp = null; // to deference the node and let garbage collector to delete/clear this node
break; // don't return here otherwise size-- won't execute
}
temp = temp.next;
}
Before referencing temp.next and temp.previous as lvalue you should check whether they are null otherwise it will throw NullPointerException.
Hope it helps!
You have to find Node object whose data is equal to T num. Use such loop:
for (Node<T> x = first; x != null; x = x.next) {
if (num.equals(x.data)) {
unlink(x);
return true;
}
}
Where first is pointer to first node. In method remove you have to unlink found Node x from linked list:
T remove(Node<T> x) {
// assert x != null;
final T element = x.data;
final Node<T> next = x.next;
final Node<T> prev = x.prev;
if (prev == null) {
//if x is first node(head)
first = next;
} else {
// link x.next to x.prev.next
prev.next = next;
//unlink x
x.prev = null;
}
if (next == null) {
//if x is last node(tail)
last = prev;
} else {
// link x.prev to x.next.prev
next.prev = prev;
//unlink x
x.next = null;
}
// reset data
x.data = null;
size--;
return element;
}
I'm trying to Insert Sort random integers into the linked list from smallest to largest. Every time I run this method it will begin sorting and printing but will eventually give me a nullpointerexception? Any help is appreciated.
public void insertInOrder(int x) {
if (head == null) {
head = new Node(x);
} else {
Node prev;
Node curr;
for (prev = null, curr = head;
(curr != null) && (x > curr.getNumber());
prev = curr, curr = curr.getNext()) {}
if (prev == null) {
insertAtHead(x);
}
if (curr == null) {
insertAtTail(x);
} else {
Node nNex = new Node(x);
nNex.setNext(curr);
prev.setNext(nNex); // NullPointerException is raised here
}
}
}
You should do an if, else if, and else statement instead of a double if and else:
This is what you have
if (prev == null) {
insertAtHead(x);
}
if (curr == null) {
insertAtTail(x);
} else {
Node nNex = new Node(x);
nNex.setNext(curr);
prev.setNext(nNex);
}
You check if prev is null, If it is it goes in the first if statement, but if curr is null, when you enter the else statement prev is still null. You should do:
if (prev == null) {
insertAtHead(x);
}
else if (curr == null) {
insertAtTail(x);
} else {
Node nNex = new Node(x);
nNex.setNext(curr);
prev.setNext(nNex);
}
I am having a little bit of difficulties with the Recursive concept.
Given a LinkedList with Integer values
L1 = (2->1->4->6->3)
L2= (1->9->6->3)
The function should remove the Odd numbers from the linkedlist starting at the integer N and returns a reference to the new head
i.e
L1.deleteOdd(2) = > (2->4->6)
L2.deleteOdd(1) = > (6)
I implemented a normal iterative function that does the job, here it is
public node deleteOdd(int n) {
node head = this.head;
if (head == null)
return head;
while (head != null) {
if (head.data == n) {
node head2 = head;
while (head2.next != null) {
if (head2.next.data % 2 != 0) {
head2.next = head2.next.next;
} else {
head2 = head2.next;
}
}
if (head.data % 2 != 0) {
return head.next;
}
return head;
}
head = head.next;
}
return head;
}
Now I am trying to do a recursive function, I tried doing something but it seems like I am missing something.
My recursive function is
public node DeleteOddR(int n) {
node head = this.head;
if (head == null)
return head;
if (head != null) {
if (head.data == n) {
node head2 = head;
if (head2.next.data % 2 != 0)
{
head2.next = head2.next.next;
} else {
head2 = head2.next;
}
if (head.data % 2 != 0) {
return DeleteOddR(head.next.data);
} else {
head.next = DeleteOddR(head.next.data);
return head;
}
} else {
head = head.next;
}
}
return head;
}
The results is
node f = l1.DeleteOddR(2);
display(f); // Gives- >2->3->4->6
I would appreciate helps..
I write one may meet your requirement .
Save the previous node and recurse using it .
public class LinkedList{
public static void main(String[] args) {
LinkedList node0 = new LinkedList(0);
LinkedList node1 = new LinkedList(1);
LinkedList node2 = new LinkedList(2);
LinkedList node3 = new LinkedList(3);
LinkedList node4 = new LinkedList(4);
LinkedList node5 = new LinkedList(5);
LinkedList node6 = new LinkedList(6);
LinkedList node7 = new LinkedList(7);
LinkedList node8 = new LinkedList(8);
node0.setNext(node1);
node1.setNext(node2);
node2.setNext(node3);
node3.setNext(node4);
node4.setNext(node5);
node5.setNext(node6);
node6.setNext(node7);
node7.setNext(node8);
node0.removeOddFromVale(3, false);
System.out.println();
}
public void removeOddFromVale(int value,boolean start){
LinkedList head = this;
LinkedList prev = this;
if(!start){
while(head != null){
if(head.value == value){
start = true;
break;
}
prev = head;
head = head.next;
}
}
if(prev != null && head != null){
if(prev == head){
head = head.next;
}
if (head != null) {
if (head.value % 2 == 0) {
prev.next = head.next;
} else {
prev = prev.next;
head = head.next;
}
if (prev != null) {
prev.removeOddFromVale(value, true);
}
}
}
}
private LinkedList next;
private int value;
public LinkedList(int value){
this.value = value;
}
public LinkedList getNext() {
return next;
}
public void setNext(LinkedList next) {
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
This is a class lab, and within it I am attempting to add, remove, etc. into a doubly linked list. I have what I believe to be correct with what I have. I am having problems figuring out how to remove an object if its not the beginning or end of the list. I am having similar issues with the add method. Any advice on where to go from here and comments on my current code is very appreciated.
public class Double<T extends Comparable<T>> implements ListInterface<T> {
protected DLLNode<T> front; //Front of list
protected DLLNode<T> rear; //Rear of list
protected DLLNode<T> curPosition; //Current spot for iteration
protected int numElements; //Number of elements in list
public Double() {
front = null;
rear = null;
curPosition = null;
numElements = 0;
}
protected DLLNode<T> find(T target) {
//While the list is not empty and the target is not equal to the current element
//curr will move down the list. If curr becomes null then return null.
//If it finds the element, return it.
DLLNode<T> curr;
curr = front;
T currInfo = curr.getInfo();
while(curr != null && currInfo.compareTo(target) != 0) {
curr = (DLLNode<T>)curr.getLink();
}
if (curr == null) {
return null;
}
else {
return curr;
}
}
public int size() {
//Return number of elements in the list
return numElements;
}
public boolean contains(T element) {
//Does the list contain the given element?
//Return true if so, false otherwise.
if (find(element) == null) {
return false;
}
else {
return true;
}
}
public boolean remove(T element) {
//While the list is not empty, curr will move down. If the element can not
//be found, then return false. Else remove the element.
DLLNode<T> curr;
curr = front;
T currInfo = curr.getInfo();
while(curr != null) {
curr = (DLLNode<T>)curr.getLink();
}
if (find(element) == null) {
return false;
}
else {
if (curr == null) {
curr = curr.getBack();
curr = rear;
}
else if (curr == front) {
curr = (DLLNode<T>)curr.getLink();
curr = front;
}
else if (curr == rear) {
curr = curr.getBack();
curr = rear;
}
else {
}
return true;
}
}
public T get(T element) {
//Return the info of the find method.
if (find(element) == null) {
return null;
}
else {
return find(element).getInfo();
}
}
//public String toString() {
//}
public void reset() {
//Reset the iteration back to front
curPosition = front;
}
public T getNext() {
//Return the info of the next element in the list
DLLNode<T> curr;
curr = front;
//while (curr != null) {
//curr = (DLLNode<T>)curr.getLink();
//}
if ((DLLNode<T>)curr.getLink() == null) {
return null;
}
else {
curr = (DLLNode<T>)curr.getLink();
return curr.getInfo();
}
}
public void resetBack() {
}
public T getPrevious() {
//Return the previous element in the list
DLLNode<T> curr;
curr = front;
if ((DLLNode<T>)curr.getLink() == null) {
return null;
}
else if((DLLNode<T>)curr.getBack() == null) {
return null;
}
else {
curr = curr.getBack();
return curr.getInfo();
}
}
public void add(T element) {
//PreCondition: Assume the element is NOT already in the list
//AND that the list is not full!
DLLNode<T> curr;
DLLNode<T> newNode = (DLLNode<T>)element;
curr = front;
if (curr == null) {
front = (DLLNode<T>)element;
}
else {
}
}
}
This is the target main function eventually:
public static void main(String[] args){
Double<String> d = new Double<String>();
d.add("Hello");
d.add("Arthur");
d.add("Goodbye");
d.add("Zoo");
d.add("Computer Science");
d.add("Mathematics");
d.add("Testing");
System.out.println(d);
System.out.println( "Contains -Hello- " + d.contains("Hello"));
System.out.println("Contains -Spring- " + d.contains("Spring"));
System.out.println("size: " + d.size());
d.resetBack();
for (int i = 0; i < d.size(); i++){
String item = (String)d.getPrevious();
System.out.println(item);
} //good stopping point
d.remove("Zoo");
d.remove("Arthur");
d.remove("Testing");
System.out.println("size: " + d.size());
System.out.println(d);
d.remove("Goodbye");
d.remove("Hello");
System.out.println(d);
d.remove ("Computer Science");
d.remove("Mathematics");
System.out.println(d);}
}
I don't know what your DLLNode class looks like, but it probably looks like
class DLLNode {
DLLNode next;
DLLNode prev;
}
To remove a node, the logic would be
next.prev = prev;
prev.next = next;
To add a node newNode following a node, the logic is
newNode.prev = this;
newNode.next = next;
next = newNode;
I haven't done any null pointer checks, that's up to you.