Delete element of singly linked list - java

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");
}

Related

Null pointer exception while deleting an element from doubly linked list

The code is working fine when I try to delete any element for some indices but for some others it is not working. For example, Whenever I try to delete by passing delete(1) it may work and if I try with delete(2) it may show NullPointerException. Here is the code :
Node head;
public void insert(int data)
{
Node node = new Node();
node.data = data;
node.next = null;
node.prev = null;
if(head == null)
{
head = node;
return;
}
Node n = head;
while(n.next!=null)
{
n = n.next;
}
node.prev = n;
n.next = node;
}
public void show()
{
if(head == null)
{
System.out.println("Doubly Linked List is empty so please enter values first.");
return;
}
Node n = head;
while(n.next!=null)
{
System.out.println(n.data);
n = n.next;
}
System.out.println(n.data);
}
public void delete(int index)
{
if(head == null)
{
System.out.println("List is empty.");
return;
}
if(index == 0)
{
head = head.next;
head.prev = null;
return;
}
Node n = head;
for(int i=0;i<index;i++)
{
n = n.next;
}
n.prev.next = n.next;
n.next.prev = n.prev;
}
}
So this is my code and You can see the delete method over there. I even run through debug mode, it is showing error at n.prev.next = n.next
Any kind of help is highly appreciated.
When I ran your code, the NullPointerException occurred on this line:
n.next.prev = n.prev;
and not on the line you said in your question.
The NullPointerException occurs when you delete the last Node in the list. This is because the value of next for the last Node in the list is null. So n.next is null and therefore n.next.prev throws NullPointerException.
You need to check whether n.next is null and only if it isn't you can execute the code: n.next.prev = n.prev.
Also, you need to check the value of parameter index in method delete(). One way would be to keep track of the number of elements in the list.
The below code incorporates the changes described. The parts I added are preceded by the comment Change here
public class DbLnkLst {
private static class Node {
int data;
Node next;
Node prev;
}
Node head;
public void insert(int data)
{
Node node = new Node();
node.data = data;
node.next = null;
node.prev = null;
if(head == null)
{
head = node;
return;
}
Node n = head;
while(n.next!=null)
{
n = n.next;
}
node.prev = n;
n.next = node;
}
public void show()
{
if(head == null)
{
System.out.println("Doubly Linked List is empty so please enter values first.");
return;
}
Node n = head;
while(n.next!=null)
{
System.out.println(n.data);
n = n.next;
}
System.out.println(n.data);
}
public void delete(int index)
{
// Change here.
if (index < 0) {
throw new IllegalArgumentException("negative index: " + index);
}
if(head == null)
{
System.out.println("List is empty.");
return;
}
if(index == 0)
{
head = head.next;
head.prev = null;
return;
}
Node n = head;
for(int i=0;i<index;i++)
{
// Change here.
if (n.next == null) {
throw new IllegalArgumentException("invalid index: " + index);
}
n = n.next;
}
n.prev.next = n.next;
// Change here.
if (n.next != null) {
n.next.prev = n.prev;
}
}
/**
* For testing the class.
*/
public static void main(String[] args) {
DbLnkLst list = new DbLnkLst();
list.insert(0);
list.insert(1);
list.insert(2);
System.out.println("List is:");
list.show();
list.delete(2);
System.out.println("After 'delete(2)', list is:");
list.show();
System.out.println("Try 'delete(2)' again.");
list.delete(2);
}
}
The output from running the above code is below:
List is:
0
1
2
After 'delete(2)', list is:
0
1
Try 'delete(2)' again.
Exception in thread "main" java.lang.IllegalArgumentException: invalid index: 2
at genrlprj/misctsts.DbLnkLst.delete(DbLnkLst.java:73)
at genrlprj/misctsts.DbLnkLst.main(DbLnkLst.java:100)

Priorityqueue implemented via singly linked list insert

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

Null Pointer while Traversing through Binary Tree

I was doing an assignment in which I'm supposed to create a binary tree and define given functions from its abstract superclass (AbstractBinaryTree.java).
While working on a function called getNumbers() which is basically going to traverse through the whole tree whilst adding values from each node to an array list which it returns. There seems to be a null pointer in one of my if statements.
AbstractBinaryTree.java
import java.util.ArrayList;
public abstract class AbstractBinaryTree
{
protected Node root;
protected int sizeOfTree;
public AbstractBinaryTree()
{
root = null;
sizeOfTree = 0;
}
public int size(){ return sizeOfTree; }
/** compute the depth of a node */
public abstract int depth(Node node);
/** Check if a number is in the tree or not */
public abstract boolean find(Integer i);
/** Create a list of all the numbers in the tree. */
/* If a number appears N times in the tree then this */
/* number should appear N times in the returned list */
public abstract ArrayList<Integer> getNumbers();
/** Adds a leaf to the tree with number specifed by input. */
public abstract void addLeaf(Integer i);
/** Removes "some" leaf from the tree. */
/* If the tree is empty should return null */
public abstract Node removeLeaf();
// these methods are only needed if you wish
// use the TreeGUI visualization program
public int getheight(Node n){
if( n == null) return 0;
return 1 + Math.max(
getheight(n.getLeft()) , getheight(n.getRight())
);
}
public int height(){ return getheight(root); }
}
Node.java File.
public class Node{
protected Integer data;
protected Node left;
protected Node right;
public Node(Integer data)
{
this.data = data;
this.left = this.right = null;
}
public Node(Integer data, Node left, Node right){
this.data = data;
this.left = left;
this.right = right;
}
public Integer getData(){ return this.data; }
public Node getLeft(){ return this.left; }
public Node getRight(){ return this.right; }
public void setLeft(Node left){ this.left = left; }
public void setRight(Node right){ this.right = right; }
public void setData(Integer data){ this.data = data; }
}
BinaryTree.java
import java.util.ArrayList;
import java.util.*;
// Student Name: Adrian Robertson
// Student Number: 101020295
//
// References: Collier, R. "Lectures Notes for COMP1406C- Introduction to Computer Science II" [PDF documents]. Retrieved from cuLearn: https://www.carleton.ca/culearn/(Winter2016).//
// References: http://codereview.stackexchange.com/questions/13255/deleting-a-node-from-a-binary-search-tree
// http://www.algolist.net/Data_structures/Binary_search_tree/Removal
// http://www.geeksforgeeks.org/inorder-tree-traversal- without-recursion-and-without-stack/
public class BinaryTree extends AbstractBinaryTree
{
protected Node root = new Node(12);
public static BinaryTree create()
{
BinaryTree tempTree = new BinaryTree();
//creating all the nodes
Node temp10 = new Node(10);
Node temp40 = new Node(40);
Node temp30 = new Node(30);
Node temp29 = new Node(29);
Node temp51 = new Node(51);
Node temp61 = new Node(61);
Node temp72 = new Node(72);
Node temp31 = new Node(31);
Node temp32 = new Node(32);
Node temp42 = new Node(42);
Node temp34 = new Node(34);
Node temp2 = new Node(2);
Node temp61x2 = new Node(61);
Node temp66 = new Node(66);
Node temp3 = new Node(3);
Node temp73 = new Node(73);
Node temp74 = new Node(74);
Node temp5 = new Node(5);
//setting up the tree
if (tempTree.root.getData() == null)
{
tempTree.root.setData(12);
tempTree.root.setLeft(temp10);
tempTree.root.setRight(temp40);
}
temp10.setLeft(temp30);
temp30.setRight(temp29);
temp29.setRight(temp51);
temp51.setLeft(temp61);
temp51.setRight(temp72);
temp40.setLeft(temp31);
temp31.setLeft(temp42);
temp31.setRight(temp34);
temp34.setLeft(temp61x2);
temp61x2.setLeft(temp66);
temp61x2.setRight(temp73);
temp40.setRight(temp32);
temp32.setRight(temp2);
temp2.setLeft(temp3);
temp3.setRight(temp74);
temp74.setLeft(temp5);
return tempTree;
}
public int depth(Node node)
{
Node current = this.root;
int counter = 1;
while(node != current)
{
if (node.getData() > current.getData())
current = current.getRight();
if (node.getData() < current.getData())
current = current.getLeft();
}
return counter;
}
public boolean find(Integer i)
{
boolean found = false;
Node current = this.root;
if (i == current.getData())
found = true;
while (i != current.getData())
{
if (i > current.getData())
current = current.getRight();
if (i < current.getData())
current = current.getLeft();
if (i == current.getData())
found = true;
}
return found;
}
public ArrayList<Integer> getNumbers()
{
ArrayList<Integer> temp = new ArrayList<Integer>();
Node current = this.root;
Node Pre = new Node(null);
while (current.getData() != null )
{
if (current.getLeft().getData() == null)
{
temp.add(current.getData());
current = current.getRight();
}
else
{
/* Find the inorder predecessor of current */
Pre = current.getLeft();
while(Pre.getRight() != null && Pre.getRight() != current)
Pre = Pre.getRight();
/* Make current as right child of its inorder predecessor */
if (Pre.getRight() == null)
{
Pre.setRight(current);
current = current.getLeft();
}
/* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */
else
{
Pre.setRight(null);
temp.add(current.getData());
current = current.getRight();
}/* End of if condition Pre.right == NULL */
}/* End of if condition current.left == NULL*/
}/*End of while */
Collections.sort(temp);
return temp;
}
public void addLeaf(Integer i)
{
insert(this.root, i);
}
public static void insert(Node node, int value) //insert a node Based on provided argument where node is the root of tree
{
if (node == null)
{
Node first = new Node(value);
node = first;
}
else if (value < node.getData())
{
if (node.left != null)
{
insert(node.left, value);
}
else
{
System.out.println(" > Inserted " + value + " to left of node " + node.getData());
Node newNode = new Node(value);
node.left = newNode;
}
}
else if (value > node.getData())
{
if (node.right != null)
{
insert(node.right, value);
}
else
{
System.out.println(" > Inserted " + value + " to right of node " + node.getData());
Node newNode = new Node(value);
node.right = newNode;
}
}
}
public Node removeLeaf()
{
Node tempA = new Node(61); //create a new node with that value
deleteNodeBST(this.root, 61); //delete the node containing that leaf value
return tempA; //return the copy of that node
}
//delete given node with given value
public boolean deleteNodeBST(Node node, int data) {
ArrayList<Integer> temp = this.getNumbers();
if (node == null) {
return false;
}
if (node.getData() == data) {
if ((node.getLeft() == null) && (node.getRight() == null)) {
// leaf node
node = null;
return true;
}
if ((node.getLeft() != null) && (node.getRight() != null)) {
// node with two children
node.setData(temp.get(0));
return true;
}
// either left child or right child
if (node.getLeft() != null) {
this.root.setLeft(node.getLeft());
node = null;
return true;
}
if (node.getRight() != null) {
this.root.setRight(node.getRight());
node = null;
return true;
}
}
this.root = node;
if (node.getData() > data) {
return deleteNodeBST(node.getLeft(), data);
} else {
return deleteNodeBST(node.getRight(), data);
}
}
public static void main(String args[])
{
BinaryTree myTree = new BinaryTree();
myTree.create();
System.out.println(myTree.getNumbers());
}
}
The create function creates a binary tree and returns that binary tree. This is the predefined binary tree that I was supposed to create according to assignment guidelines. I understand that the tree values are not organised properly as they would be in a proper binary tree. Is that was causes the null pointer during traversal? Cause the traversal is taylored to work for a proper Binary tree.
In class BinaryTree, you initialize the left and right of your root node only if the haven't data. But the root node is create with data...
You should invert the condition in :
//setting up the tree
if (tempTree.root.getData() == null)
And add a test in getNumbers() :
if (current.getLeft() == null || current.getLeft().getData() == null)
In the BinaryTree class, getNumbers() method and while loop. Maybe your problem is here:
if (current.getLeft().getData() == null) {
temp.add(current.getData());
current = current.getRight();
}
When you call current.getLeft(), it will return null when the left Node is null. And then, you call getData() it will throw a NullPointerException. If you're not sure that it always not null check it before you call any methods of it. Example you can change the if statement to:
if (current.getLeft() != null && current.getLeft().getData() == null) {
temp.add(current.getData());
current = current.getRight();
}
Or:
Node left = current.getLeft();
if (left == null) {
//TODO something here
} else if (left.getData() == null) {
temp.add(current.getData());
current = current.getRight();
}
Please update your getNumbers - method accordingly,
You need to put right checks before work with reference type.
public ArrayList<Integer> getNumbers()
{
ArrayList<Integer> temp = new ArrayList<Integer>();
Node current = this.root;
Node Pre = new Node(null);
while (current != null && current.getData() != null ) // Fix here... Add : current != null
{
if (current.getLeft() != null && current.getLeft().getData() == null) // Fix here... Add : current.getLeft() != null
{
temp.add(current.getData());
current = current.getRight();
}
else
{
/* Find the inorder predecessor of current */
Pre = current.getLeft();
while(Pre != null && Pre.getRight() != null && Pre.getRight() != current) // Fix here... Add : Pre != null
Pre = Pre.getRight();
/* Make current as right child of its inorder predecessor */
if (Pre != null && Pre.getRight() == null) // Fix here... Add : Pre != null
{
Pre.setRight(current);
current = current.getLeft();
}
/* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */
else
{
if(Pre != null){ // Fix here... Add : Pre != null
Pre.setRight(null);
}
temp.add(current.getData());
current = current.getRight();
}/* End of if condition Pre.right == NULL */
}/* End of if condition current.left == NULL*/
}/*End of while */
Collections.sort(temp);
return temp;
}

Construct a no recursive insert method for binary tree

I have completed the recursive insert function and it works perfectly, but I can not get the non recursive solution to work.
public void insert(T item){
root= nonRecursive(root,item);
}
public BinaryTreeNode<T> nonRecursive(BinaryTreeNode<T> tree, T item){
if(root==null){
root=new BinaryTreeNode<T>(item);
return root;
}
else{
BinaryTreeNode<T> next = new BinaryTreeNode<T>();
Comparable<T> temp = (Comparable<T>) root.info;
if(temp.compareTo(item)== 0){
return null;
}
else if(temp.compareTo(item) > 0){
next=root.lLink;
}
else{
next=root.rLink;
}
while(next != null){
Comparable<T> temp2 = (Comparable<T>) next.info;
if(temp.compareTo(item) == 0){
return null;
}
else if(temp2.compareTo(item) > 0){
next=next.lLink;
}
else{
next=next.rLink;
}
}
next=new BinaryTreeNode<T>(item);
return root;
}
}
and then the recursive one is:
public void insert(T item) {
root = recInsert(root, item);
}
public BinaryTreeNode<T> recInsert(BinaryTreeNode<T> tree, T item) {
if(tree == null) {
//create new node
tree = new BinaryTreeNode<T>(item);
}
else {
Comparable<T> temp = (Comparable<T>) tree.info;
if (temp.compareTo(item) == 0) {
System.err.print("Already in ­ duplicates are not allowed.");
return null;
}
else if (temp.compareTo(item) > 0)
tree.lLink = recInsert(tree.lLink, item);
else
tree.rLink = recInsert(tree.rLink, item);
}
return tree;
}
does anyone know what I am doing wrong?
I thought I had gotten it but now it only returns the first number I enter in
here you go then
in your code,
if(current == null){
current.lLink=node;
if current is null, then how can it have a iLink ?
maybe you need to do
if(current == null){
current = new Node ();
current.lLink=node;
Your code is not even close to finish.
You haven't even done one comparison. What you did is simply meaningless loops.
If you are looking for a non-recursive logic, here is the pseudo code. Your job is to understand it and write it in Java.
insert(item) {
Node itemNode = new Node(item);
if root is null {
root = itemNode
return
}
currentNode = root;
keep looping until node is inserted {
if currentNode is equals to itemNode {
show error and exit
} else if itemNode is smaller than currentNode {
if (currentNode has no left){
set currentNode's left to itemNode
// Item Inserted!!!!
} else { // there are node at currentNode's left
set currentNode to currentNode's left (and continue lookup)
}
} else { // item node is greater than current node
// do similar thing as the "itemNode < currentNode logic",
// of course on currentNode's right
}
}
}

Doubly Linked List -Removal and Adding

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.

Categories

Resources