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);
}
Related
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);
}
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 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;
}
}
such that If the element to be deleted is the first element of the list and the list contains only one element, you only need to assign null to the pfirst and plast. If the element to be deleted is the first element of the list and the list contain more than one element, you need a temporary variable to point to the pfirst then move the pfirst to point to its next element and set the temporary variable to null.
Here is my code that is not working as expected
Question is not clear in it's present format. If you are trying to do some custom operation/s on a list better wrap a list interface and perform operation on the list
import java.util.List;
public class SinglyList<T>
{
List<T> list;
private SinglyList(List<T> list)
{
super();
this.list = list;
}
public T delete(){
return list.remove(0);
}
}
Swift program to delete element of a single linked list
import UIKit
class Node<T: Equatable>{
var value:T?
var nextNode:Node?
}
class LinkedList<T: Equatable>{
var headNode: Node = Node<T>()
func insert(value: T){
if self.headNode.value == nil{
print("The item \(value) is inserted")
self.headNode.value = value
}else{
var lastNode = self.headNode
while lastNode.nextNode != nil {
lastNode = lastNode.nextNode!
}
let newNode = Node<T>()
newNode.value = value
print("The item \(value) is inserted")
lastNode.nextNode = newNode
}
}
func remove(value: T){
if self.headNode.value == value{
print("The item \(value) is removed")
if self.headNode.nextNode != nil{
self.headNode = self.headNode.nextNode!
}else{
self.headNode.value = nil
}
}else{
var lastNode = self.headNode
var found = true
while lastNode.nextNode?.value != value{
if lastNode.nextNode != nil{
lastNode = lastNode.nextNode!
}else{
found = false
break
}
}
if found{
print("The item \(value) is removed")
if lastNode.nextNode?.nextNode != nil{
lastNode.nextNode = lastNode.nextNode?.nextNode!
}else{
//if at the end, the next is nil
lastNode.nextNode = nil
}
}else{
print("---------------")
print("The item \(value) is not found")
print("---------------")
}
}
}
func printAllKeys() {
var currentNode: Node! = headNode
print("---------------")
print("Items in LINKED LIST")
while currentNode != nil && currentNode.value != nil {
print(currentNode.value!)
currentNode = currentNode.nextNode
}
print("---------------")
}
}
var linkedList = LinkedList<Int>()
linkedList.insert(value: 10)
linkedList.insert(value: 20)
linkedList.insert(value: 30)
linkedList.insert(value: 40)
linkedList.insert(value: 50)
linkedList.printAllKeys()
linkedList.remove(value: 10)
linkedList.printAllKeys()
linkedList.remove(value: 30)
linkedList.printAllKeys()
linkedList.remove(value: 40)
linkedList.printAllKeys()
linkedList.remove(value: 40)
linkedList.printAllKeys()
it seams your question is incomplete because it doesnt have the code with it bu as well i can demonstrate you how to implement and delete a list
public class SinglyLinkedList {
public void addLast(SinglyLinkedListNode newNode) {
if (newNode == null)
return;
else {
newNode.next = null;
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
}
public void addFirst(SinglyLinkedListNode newNode) {
if (newNode == null)
return;
else {
if (head == null) {
newNode.next = null;
head = newNode;
tail = newNode;
} else {
newNode.next = head;
head = newNode;
}
}
}
public void insertAfter(SinglyLinkedListNode previous,
SinglyLinkedListNode newNode) {
if (newNode == null)
return;
else {
if (previous == null)
addFirst(newNode);
else if (previous == tail)
addLast(newNode);
else {
SinglyLinkedListNode next = previous.next;
previous.next = newNode;
newNode.next = next;
}
}
}
}
include this method in the same class
// delete an item from the linked list
public void delete(int pos)
{
if (countitem() > 0){
//make sure the list is not empty.
ListNode<T> temp,del;
if (pos== 1){
//delete the first item
if(countitem()==1){ //The list contains only one item
pfirst=null;
plast=null;
}else
{
//The list contains more than one item
temp=pfirst;
pfirst=pfirst.next;
temp=null;
}
System.out.println("Deleted");
}
else if (pos > 1 && pos <=countitem()){
//delete middle item
temp=pfirst;
int i;
for(i=1;i<pos-1;i=i+1)
{temp=temp.next;} //move to the item staying before the target item to be deleted
del=temp.next; //target item to be deleted
temp.next=del.next;
if(del.next==null)
plast=temp; //delete last item
del=null;
System.out.println("Deleted");
}
else System.out.println("Invalid position!");
}
else System.out.println("No item found");
}
I'm trying to make a tree, in a way such that the left child of a terminal(leaf node) node.
link to see what tree should look like.
I've gotten an inorder version of the code i want, its a simple insert function that threads the tree ,but now my problem is changing this code into a preOrder insert.
This i can do, but my main problem is finding the preorder successor, which is all the way in a other sub tree, do any of you guys know a simple way to get the preorder successor?
//in-order insert
if (root == null) { // tree is empty
root = newNode;
return;
}
PreNode<T> p = root, prev = null;
while (p != null) { // find a place to insert newNode;
prev = p;
if (info.compareTo(p.info) < 0)
p = p.left;
else if (!p.hasThread) // go to the right node only if it is
p = p.right; // a descendant, not a successor;
else break; // don't follow successor link;
}
if (info.compareTo(prev.info) < 0) { // if newNode is left child of
prev.left = newNode; // its parent, the parent becomes
newNode.hasThread = true; // also its successor;
newNode.right = prev;
}
else if (prev.hasThread) { // if parent of the newNode
newNode.hasThread = true; // is not the right-most node,
prev.hasThread = false; // make parent's successor
newNode.right = prev.right; // newNode's successor,
prev.right = newNode;
}
else prev.right = newNode; // otherwise has no successor;
This will work, assuming that there is a Node class which has right&left references to its children as well as a boolean variable ht which indicates if it has a thread or not.
public void insert(T info) {
PreNode<T> newNode = new PreNode<T>(info);
if (root == null) {
root = newNode;
return;
}
PreNode<T> curr = root, r = null, l = null;
while (true) {
if (info.compareTo(curr.info) < 0) {
if (curr.right != null)
r = curr.right;
if (curr.left == null || curr.ht) {
newNode.left = r;
curr.left = newNode;
curr.ht = false;
return;
} else
curr = curr.left;
} else {
if (curr.left != null && !curr.ht)
l = curr.left;
if (curr.right == null) {
if (curr.ht) {
newNode.left = curr.left;
newNode.ht = true;
curr.left = null;
curr.right = newNode;
curr.ht = false;
return;
} else
newNode.left = r;
curr.right = newNode;
curr.ht = false;
if (l != null) {
while (!l.ht) {
if (l.right != null)
l = l.right;
else
l = l.left;
}
l.left = newNode;
l.ht = true;
return;
}
} else
curr = curr.right;
}
}
}