Deleting a specific node in a singly linked list(java) - java

So my problem is that I wanna delete a node based on a value inputted by the user, in my program I can already, add, search, and delete the node in the last position, but so far I haven't been able to delete a specific value inputted by the user, if for example I have 1,2,3,4 elements in my list I wanna be able to point at, say 2, and delete it. here are my functions, the last one is the uncompleted one:
//searches node
public void searchNode(int input){
Node temp = first;
boolean found = false;
if(!isEmpty()){
for(int i = 0 ; i<size ; i ++){
if(temp.value == input){
System.out.println(input + " found in the position: " + (i+1));
found = true;
break;
}
temp = temp.rightNode;
}
if(!found)
System.out.println("value not found.");
}
}
//deletes last node
public void deleteLastNode(){
if(isEmpty()){
System.out.println("There are no nodes to delete.");
}
if(last == first){
first = null;
last = null;
} else {
Node current = first;
while(current.rightNode != last){
current = current.rightNode;
}
current.rightNode = null;
last = current;
}
size --;
}
//delete element, input by user.
public void deleteInputByUser(int input) {
Node temp = first;
boolean found = false;
if(isEmpty()){
System.out.println("There are no nodes to delete.");
} else {
}
size--;
}
//Node class
public class Node{
int value;
Node rigthNode;
public Node(int value){
this.value = value;
}
}

Deletion of a node in a Linked List by value is not so bad. This pseudocode should help you get started:
deleteNodeByValue(int val) {
if (head.val = val) {
head = head.next
return
}
current = head
while (current.next != null) {
if (current.next.val = val) {
current.next = current.next.next
return
}
current = current.next
}
}

Find the nodeToDelete and his previousNode, then
previousNode.rightNode = nodeToDelete.rightNode;

you can do it this way. The following code will remove the element once the index is given.
public boolean deleteAt(int index){
Node current=first;
if(index==0){
first=current.rightNode;
return true;
}
currentIndex=0;
previousNode=first;
current=first.rightNode;
while(current!=null){
if(currentIndex==index){
previousNode.rightNode=current.rightNode;
return true;
}
currentIndex++;
previousNode=current;
current=current.rightNode;
}
return false;
}

You could try something like that.
public void deleteNodeByValue(int input) {
Node currNode = first;
boolean found = false;
Node prevNode = first;
if (!isEmpty()) {
for (int i = 0; i < size; i++) {
if (currNode.value == input) {
///////DELETE START
if (currNode == first) {
first = currNode.rightNode;
} else {
prevNode.rightNode = currNode.rightNode;
if (currNode == last)
last = prevNode;
}
////DELETE END
found = true;
size--;
break;
}
prevNode = currNode;
currNode = currNode.rightNode;
}
if (!found)
System.out.println("value not found.");
}
}

Related

trouble implementing a linked list in java

I tried to implement a linked list in java using the code below:
class Linkedlist<T>{
private node head, tail;
public Linkedlist(){
head = new node(null);
tail = head;
}
public boolean insert(T value){
if(head.getValue() == null){
this.head.setValue(value);
head.setNext(null);
return true;
}
node insertNode = new node(value);
tail.setNext(insertNode);
tail = insertNode;
return true;
}
public boolean insert(T value, int index) {
if ( sizeOfList() == index + 1 ) return false;
node temp = this.head.getNext();
node prvtmp = this.head;
for (int i = 0; i <= index; i++) {
temp = temp.getNext();
prvtmp = temp;
System.out.println("for loop");
}
node insertNode = new node(value);
System.out.println("node created");
prvtmp.setNext(insertNode);
insertNode.setNext(temp);
System.out.println("temps");
return true;
}
public int sizeOfList(){
int size = 0;
node temp = this.head;
while(temp.getNext() != null){
temp = temp.getNext();
size++;
}
return size;
}
public String[] rtrnList(){
node temp = this.head;
int listSize = sizeOfList();
String[] resualt = new String[listSize + 1];
for (int i = 0;i <= listSize;i++){
resualt[i] = String.valueOf(temp.getValue());
temp = temp.getNext();
}
return resualt;
}
}
Class node:
public class node<T> {
private T value;
private node next;
public node(T value){
this.value = value;
this.next = null;
}
public void setValue(T value) {
this.value = value;
}
public void setNext(node next) {
this.next = next;
}
public T getValue() {
return value;
}
public node getNext() {
return next;
}
}
When I try to run the insert method with one argument it works fine, but when I run it with two arguments:
import java.util.Arrays;
public class main {
public static void main(String[] args){
Linkedlist list = new Linkedlist();
list.insert(2);
list.insert(2);
list.insert(2);
list.insert(2);
list.insert(2);
list.insert(2);
list.insert(11, 3);
System.out.println(Arrays.toString(list.rtrnList()));
System.out.println("finished");
}
}
The program doesn't reach the line that prints finished, but if we delete the line: list.insert(11, 3);
Then the program works just fine.
output:
for loop
for loop
for loop
for loop
node created
finish insert
The problems is inside the for loop of your insert(T value, int index) method when you are updating the value of prvtm and temp. In your code you are first setting the value of temp to temp.getnext() and as the temp is already changed setting prvtmp to temp creating a loop which is why when you are trying to print the list it's getting into an infinite loop while calculating the size of the list.
Just put the prvtmp = temp line before temp = temp.getNext() like following code snippet. This will solve the problem.
public boolean insert(T value, int index) { // 2 2 2 2 2 2
if ( sizeOfList() == index + 1 ) return false;
node temp = this.head.getNext();
node prvtmp = this.head;
for (int i = 0; i <= index; i++) {
prvtmp = temp;
temp = temp.getNext();
System.out.println("for loop");
}
node insertNode = new node(value);
System.out.println("node created");
prvtmp.setNext(insertNode);
insertNode.setNext(temp);
System.out.println("temps");
return true;
}
Also if you are trying to insert in the given index update the condition of the for loop from:
i <= index to i < index - 1
Happy coding!
while inserting there is a cyclic refrence made , you can use this code for above purpose
public boolean insert(T value, int index) {
if(index > sizeOfList())
{
return false;
}
else if(index == sizeOfList())
{
if(insert(value))
return true;
else
return false;
}
else
{
node previous = this.head;
for (int i = 1; i <= index; i++) {
if(i==index-1)
{
node newnode = new node(value);
newnode.setNext(previous.getNext());
previous.setNext(newnode);
break;
}
previous = previous.getNext();
}
}
return true;
}
Output
[2, 2, 11, 2, 2, 2, 2]

Circular Linked List In Ascending Order Java

My task is to implement a circular linked list in java (ascending order) but the problem is that it is going in an infinite loop
I have created a class of Node in which i have define two elements.
public class Node {
public int element;
public Node next;
public class Node {
int element;
Node next;
}
}
Now in the second class of List i have made a insert function i have define a Node head=null in the start and create a new nNode .After that i am checking in the head section if head==null then the first element will be nNode. After inserting the first element i will compare the next element and the head element if the head element is greater than it will shift next and the new nNode will be the head. Since it is the circular linked list it is working but it is also going in an infinite loop.
This is the List class in which i have use the node class variables
public class List {
void insert(int e) {
Node nNode = new Node();
Node tNode = head;
nNode.element = e;
if (head == null)
head = nNode;
else if (head.element > e) {
nNode.next = head;
head=nNode;
} else {
Node pNode = head;
while (tNode.next != head && tNode.element <= e) {
pNode = tNode;
tNode = tNode.next;
}
pNode.next = nNode;
nNode.next = tNode;
tNode.next=head;
}
}
}
I have created on sample program for circular linkedlist which hold name and age of given element.
It has add(), remove() and sorbasedOnAge() (Sorting is implemented by first getting clone and convert it into simple linked list. Then use merge sort so that performance of O(nLogn) could be achieved.)
If you like it don't forget to press like button.
package com.ash.practice.tricky;
import java.util.Collections;
import java.util.LinkedList;
public class CircularLinkedList implements Cloneable{
Node start;
public Node getHead() {
return start;
}
CircularLinkedList setHead(Node startNode) {
start = startNode;
return this;
}
public void add(String name, int age) {
if(name==null) {
System.out.println("name must not be null.");
return;
}
if(start == null) {
Node node = new Node(name,age);
start = node;
node.next = start;
} else {
Node node = new Node(name,age);
Node temp = start;
while(temp.next != start) {
temp = temp.next;
}
temp.next = node;
node.next = start;
}
}
public CircularLinkedList clone()throws CloneNotSupportedException{
return (CircularLinkedList)super.clone();
}
public boolean remove(String name) {
if(name==null) {
return false;
} else if(start==null) {
return false;
} else if(start.getName().equals(name)) {
if(size()>1) {
Node temp = start;
while(temp.next!=start) {
temp = temp.next;
}
temp.next = start.next;
start = start.next;
} else {
start = null;
}
return true;
} else {
Node temp = start;
Node next = null;
Node prev = null;
while(temp.next != start) {
String currName = temp.name;
if(currName.equals(name)) {
next = temp.next;
break;
} else {
temp = temp.next;
}
}
if(next == null) {
return false;
}
prev = temp.next;
while(prev.next!=temp) {
prev = prev.next;
}
prev.next = next;
temp = null;
return true;
}
}
/*
public Node getPrevious(String name, int age) {
Node curr = new Node(name,age);
Node temp = curr;
while(temp.next!=curr) {
temp = temp.next;
}
return temp;
}
*/
public int size() {
int count = 1;
if(start != null) {
Node temp = start;
while(temp.next!=start) {
count++;
temp = temp.next;
}
} else return 0;
return count;
}
public int listSize() {
int count = 1;
if(start != null) {
Node temp = start;
while(temp.next!=null) {
count++;
temp = temp.next;
}
} else return 0;
return count;
}
public void display() {
if(start == null) {
System.out.println("No element present in list.");
} else {
Node temp = start;
while(temp.next != start) {
System.out.println(temp);
temp = temp.next;
}
System.out.println(temp);
}
}
public void displayList() {
if(start == null) {
System.out.println("No element present in list.");
} else {
Node temp = start;
while(temp.next != null) {
System.out.println(temp);
temp = temp.next;
}
System.out.println(temp);
}
}
public Node getPrevious(Node curr) {
if(curr==null) {
return null;
} else {
Node temp = curr;
while(temp.next!=curr) {
temp = temp.next;
}
return temp;
}
}
Node getMiddle() {
Node result = null;
Node temp = start.next;
result = start.next;
Node end = getPrevious(start);
end.next = null;
while(temp.next!=null) {
if(temp.next.next!=null) {
temp = temp.next.next;
result = result.next;
} else {
return result;
}
}
return result;
}
private static CircularLinkedList SortCollections(CircularLinkedList list) {
return SortCollections.doSortBasedOnAge(list);
}
private static class Node {
Node next;
String name;
int age;
Node(String name,int age) {
this.name = name;
this.age = age;
}
String getName() {
return name;
}
int getAge() {
return age;
}
public String toString() {
return "name = "+name +" : age = "+age;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
private static class SortCollections {
static Node mergeSort(Node head) {
if(head == null || head.next == null) {
return head;
}
Node middle = getMiddle(head);
Node nextHead = middle.next;
middle.next = null;
Node left = mergeSort(head);
Node right = mergeSort(nextHead);
Node sortedList = sortedMerged(left, right);
return sortedList;
}
public static CircularLinkedList doSortBasedOnAge(CircularLinkedList list) {
CircularLinkedList copy = null;
try {
copy = list.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
if(copy!=null) {
Node head = copy.getHead();
Node end = copy.getPrevious(head);
end.next = null;
Node startNode = mergeSort(head);
CircularLinkedList resultList = new CircularLinkedList().setHead(startNode);
return resultList;
} else {
System.out.println("copy is null");
}
return null;
}
private static Node sortedMerged(Node a, Node b) {
if(a == null) {
return b;
} else if(b == null) {
return a;
}
Node result = null;
if(a.getAge() > b.getAge()) {
result = b;
result.next = sortedMerged(a, b.next);
} else {
result = a;
result.next = sortedMerged(a.next, b);
}
return result;
}
private static Node getMiddle(Node head) {
Node result = null;
Node temp = head;
result = head;
while(temp.next!=null) {
if(temp.next.next!=null) {
temp = temp.next.next;
result = result.next;
} else {
return result;
}
}
return result;
}
}
public static void main(String[] args) {
CircularLinkedList list = new CircularLinkedList();
Collections.sort(new LinkedList());
list.add("ashish", 90);
list.add("rahul", 80);
list.add("deepak", 57);
list.add("ankit", 24);
list.add("raju", 45);
list.add("piyush", 78);
list.add("amit", 12);
//list.display();
/*System.out.println("---------------- size = "+list.size());
System.out.println(list.remove("deepak"));
//list.display();
System.out.println("---------------- size = "+list.size());
System.out.println(list.remove("ashish"));
//list.display();
System.out.println("---------------- size = "+list.size());
System.out.println(list.remove("raju"));
//list.display();
System.out.println("---------------- size = "+list.size());
list.add("aman", 23);
System.out.println("---------------- size = "+list.size());
list.display();
System.out.println("Previous Node of second node is : "+list.getPrevious(list.start.next));
System.out.println("Previous Node of start node is : "+list.getPrevious(list.start));
System.out.println("Previous Node of piyush node is : "+list.getPrevious("piyush",78));*/
list.display();
System.out.println("---------------- size = "+list.size());
//System.out.println(list.getMiddle());
CircularLinkedList newList = CircularLinkedList.SortCollections(list);
newList.displayList();
System.out.println("---------------- size = "+newList.listSize());
}
}
Let's consider the following situation:
The list contains elements B,C,X. Now you want to insert A and then Z.
void insert(int e) {
Node nNode = new Node(); //the new node, step 1: A, step2: Z
Node tNode = head; //step1: points to B, step2: points to A
nNode.element = e;
if (head == null) { //false in both steps
head = nNode;
head.next = head; //I added this line, otherwise you'd never get a circular list
} //don't forget the curly braces when adding more than one statement to a block
else if (head.element > e) { //true in step 1, false in step 2
nNode.next = head; //A.next = A
head=nNode; //A is the new head, but X.next will still be B
} else {
//you'll enter here when adding Z
Node pNode = head; //points to A because of step 1
//when tNode = X you'll start over at B, due to error in step 1
//the condition will never be false, since no node's next will point to A
//and no node's element is greater than Z
while (tNode.next != head && tNode.element <= e) {
pNode = tNode;
tNode = tNode.next;
}
//in contrast to my previous answer, where I had an error in my thought process,
//this is correct: the node is inserted between pNode and tNode
pNode.next = nNode;
nNode.next = tNode;
tNode.next=head; //delete this
}
}
As you can see, there are at least the following problems in your code:
tNode.next=head; is not necessary, since if you insert a node between pNode and tNode, tNode.next should not be affected (and if tNode is the last node, next should already point to the head, while in all other cases this assignment would be wrong).
In the two branches above, where you set head, you're not setting the next element of the last node to head. If you don't do this when adding the first node, that's not necessarily a problem, but leaving that out when adding a new head (second condition) you'll produce an incorrect state which then might result in endless loops
What you might want to do:
Remove the tNode.next=head; statement.
If you add a new head locate the last node and set the head as its next node. That means that if you have only one node, it references itself. If you add a node at the front (your second condition) you'll have to update the next reference of the last node, otherwise you'll get an endless loop if you try to add an element at the end.
After working two days on the code I finally solved it but this is not efficient code .
void insert(int e) {
Node nNode = new Node(); //the new node, step 1: A, step2: Z
Node tNode = head; //step1: points to B, step2: points to A
nNode.element = e;
if (head == null) { //false in both steps
head = nNode;
head.next = head;
}
else if (head.element > e) { //true in step 1, false in step 2
Node pNode = head;
pNode=tNode.next; //PNode is at head which will equal to tNode.next Which will be the next element
nNode.next = head;
head=nNode;
tNode.next.next=nNode; // Now I am moving the Tail Node next
} else {
Node pNode=head; //points to A because of step 1
while (tNode.next != head && tNode.element <= e) {
pNode = tNode;
tNode = tNode.next;
}
pNode.next = nNode;
nNode.next = tNode;
}
}

deleteBack java program

I am doing some exercises on practice-it website. And there is a problem that I don't understand why I didn't pass
Write a method deleteBack that deletes the last value (the value at the back of the list) and returns the deleted value. If the list is empty, your method should throw a NoSuchElementException.
Assume that you are adding this method to the LinkedIntList class as defined below:
// A LinkedIntList object can be used to store a list of integers.
public class LinkedIntList {
private ListNode front; // node holding first value in list (null if empty)
private String name = "front"; // string to print for front of list
// Constructs an empty list.
public LinkedIntList() {
front = null;
}
// Constructs a list containing the given elements.
// For quick initialization via Practice-It test cases.
public LinkedIntList(int... elements) {
this("front", elements);
}
public LinkedIntList(String name, int... elements) {
this.name = name;
if (elements.length > 0) {
front = new ListNode(elements[0]);
ListNode current = front;
for (int i = 1; i < elements.length; i++) {
current.next = new ListNode(elements[i]);
current = current.next;
}
}
}
// Constructs a list containing the given front node.
// For quick initialization via Practice-It ListNode test cases.
private LinkedIntList(String name, ListNode front) {
this.name = name;
this.front = front;
}
// Appends the given value to the end of the list.
public void add(int value) {
if (front == null) {
front = new ListNode(value, front);
} else {
ListNode current = front;
while (current.next != null) {
current = current.next;
}
current.next = new ListNode(value);
}
}
// Inserts the given value at the given index in the list.
// Precondition: 0 <= index <= size
public void add(int index, int value) {
if (index == 0) {
front = new ListNode(value, front);
} else {
ListNode current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = new ListNode(value, current.next);
}
}
public boolean equals(Object o) {
if (o instanceof LinkedIntList) {
LinkedIntList other = (LinkedIntList) o;
return toString().equals(other.toString()); // hackish
} else {
return false;
}
}
// Returns the integer at the given index in the list.
// Precondition: 0 <= index < size
public int get(int index) {
ListNode current = front;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current.data;
}
// Removes the value at the given index from the list.
// Precondition: 0 <= index < size
public void remove(int index) {
if (index == 0) {
front = front.next;
} else {
ListNode current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
}
}
// Returns the number of elements in the list.
public int size() {
int count = 0;
ListNode current = front;
while (current != null) {
count++;
current = current.next;
}
return count;
}
// Returns a text representation of the list, giving
// indications as to the nodes and link structure of the list.
// Detects student bugs where the student has inserted a cycle
// into the list.
public String toFormattedString() {
ListNode.clearCycleData();
String result = this.name;
ListNode current = front;
boolean cycle = false;
while (current != null) {
result += " -> [" + current.data + "]";
if (current.cycle) {
result += " (cycle!)";
cycle = true;
break;
}
current = current.__gotoNext();
}
if (!cycle) {
result += " /";
}
return result;
}
// Returns a text representation of the list.
public String toString() {
return toFormattedString();
}
// ListNode is a class for storing a single node of a linked list. This
// node class is for a list of integer values.
// Most of the icky code is related to the task of figuring out
// if the student has accidentally created a cycle by pointing a later part of the list back to an earlier part.
public static class ListNode {
private static final List<ListNode> ALL_NODES = new ArrayList<ListNode>();
public static void clearCycleData() {
for (ListNode node : ALL_NODES) {
node.visited = false;
node.cycle = false;
}
}
public int data; // data stored in this node
public ListNode next; // link to next node in the list
public boolean visited; // has this node been seen yet?
public boolean cycle; // is there a cycle at this node?
// post: constructs a node with data 0 and null link
public ListNode() {
this(0, null);
}
// post: constructs a node with given data and null link
public ListNode(int data) {
this(data, null);
}
// post: constructs a node with given data and given link
public ListNode(int data, ListNode next) {
ALL_NODES.add(this);
this.data = data;
this.next = next;
this.visited = false;
this.cycle = false;
}
public ListNode __gotoNext() {
return __gotoNext(true);
}
public ListNode __gotoNext(boolean checkForCycle) {
if (checkForCycle) {
visited = true;
if (next != null) {
if (next.visited) {
// throw new IllegalStateException("cycle detected in list");
next.cycle = true;
}
next.visited = true;
}
}
return next;
}
}
// YOUR CODE GOES HERE
}
My work so far is this:
public int deleteBack(){
if(front==null){
throw new NoSuchElementException();
}else{
ListNode current = front;
while(current!=null){
current = current.next;
}
int i = current.data;
current = null;
return i;
}
}
Don't you want to iterate until the current.next is != null?
What you have now passes the entire list, and your last statements do nothing, since current is null already.
Think about the logic you have here
while(current!=null){
current = current.next;
}
When that loop exits, current == null, and then you try to access current's data. Does this point you in the right direction?
// This is the quick and dirty
//By Shewan
public int deleteBack(){
if(size()== 0){ throw new NoSuchElementException(); }
if(front==null){ throw new NoSuchElementException();
}else{
if(front.next == null){
int i = front.data;
front = null;
return i;
}
ListNode current = front.next;
ListNode prev= front;
while(current.next!=null){
prev = current;
current = current.next;
}
int i = current.data;
prev.next = null;
return i;
}
}

How to sort a Linked list

I created a linked list using nodes that prints out a list(string) of names. I'm trying to write a sort method that prints out the names in alphabetical order. If this was integers it would be easy but I have no idea how to go about doing this. Any help or tips are appreciated.
-I cannot use the builtin collections.sort(). I need to make my own method.
SortMethod: (this is what I used when I was printing a list of numbers out but now its strings so I know I can't use the > operator. I just don't know how to replace it.
public void Sort( BigNode front)
{
BigNode first,second,temp;
first= front;
while(first!=null) {
second = first.next;
while(second!=null) {
if(first.dataitems < second.dataitems)
{
temp = new BigNode();
temp.dataitems =first.dataitems;
first.dataitems = second.dataitems;
second.dataitems = temp.dataitems;
}
second=second.next;
}
Heres the rest of program(I dont think its needed but just in case)
import java.util.*;
public class BigNode {
public String dataitems;
public BigNode next;
BigNode front ;
BigNode current;
String a = "1", b = "2", c = "3", d = "4";
String[] listlength;
public void initList(){
front = null;
}
public BigNode makeNode(String number){
BigNode newNode;
newNode = new BigNode();
newNode.dataitems = number;
newNode.next = null;
return newNode;
}
public boolean isListEmpty(BigNode front){
boolean balance;
if (front == null){
balance = true;
}
else {
balance = false;
}
return balance;
}
public BigNode findTail(BigNode front) {
BigNode current;
current = front;
while(current.next != null){
//System.out.print(current.dataitems);
current = current.next;
} //System.out.println(current.dataitems);
return current;
}
public void addNode(BigNode front ,String name){
BigNode tail;
if(isListEmpty(front)){
this.front = makeNode(name);
}
else {
tail = findTail(front);
tail.next = makeNode(name);
}
}
public void addAfter(BigNode n, String dataItem2) { // n might need to be front
BigNode temp, newNode;
temp = n.next;
newNode = makeNode(dataItem2);
n.next = newNode;
newNode.next = temp;
}
public void findNode(BigNode front, String value) {
boolean found , searching;
BigNode curr;
curr = front;
found = false;
searching = true;
while ((!found) && (searching)) {
if (curr == null) {
searching = false;
}
else if (curr.dataitems == value) { // Not sure if dataitems should be there (.data in notes)
found = true;
}
else {
curr = curr.next;
}
}
System.out.println(curr.dataitems);
}
public void deleteNode(BigNode front, String value) {
BigNode curr, previous = null; boolean found;
if (!isListEmpty(front)){
curr = front;
found = false;
while ((curr.next != null) && (!found)) {
if(curr.dataitems.equals(value)) {
found = true;
}
else {
previous = curr;
curr = curr.next;
}
}
if (!found) {
if(curr.dataitems.equals(value)) {
found = true;
}
}
if (found) {
if (curr.dataitems.equals(front.dataitems)){ // front.dataitems may be wrong .dataitems
front = curr.next;
} else {
previous.next = curr.next;
}
} else {
System.out.println("Node not found!");
//curr.next = null; // Not sure If this is needed
}
}
showList(front);
}
public void printNodes(String[] len){
listlength = len;
int j;
for (j = 0; j < len.length; j++){
addNode(front, len[j]);
} showList(front);
}
public void showList(BigNode front){
current = front;
while ( current.next != null){
System.out.print(current.dataitems + ", ");
current = current.next;
}
System.out.println(current.dataitems);
MenuOptions();
}
public void MenuOptions() {
Scanner in = new Scanner(System.in);
System.out.println("Choose an Option Below:");
System.out.println(a + "(Display Length of List)" + ", " + b + "(Delete a person)" + ", " + c + ("(Exit)"));
String pick = in.nextLine();
if (pick.equals(b)) {
System.out.println("Who would you like to delete?");
String delete = in.nextLine();
deleteNode(front, delete);
}
if (pick.equals(a)) {
System.out.println("Length of List = " + listlength.length);
MenuOptions();
}
if (pick.equals(c)) {
}
}
public static void main(String[] args) {
String[] names = {"Billy Joe", "Sally Mae", "Joe Blow", "Tasha Blue", "Malcom Floyd"}; // Trying to print theses names..Possibly in alphabetical order
BigNode x = new BigNode();
x.printNodes(names);
}
}
first.dataitems.compareTo(second.dataitems)<0
or if you have a comparator
comp.compare(first.dataitems, second.dataitems)<0

LinkedSet Implementation java

We've been asked to implement a Linked Set in java. Below is my attempt, it has all the methods we are asked to write, but the method remove calls a null pointer exception without fail. Try as I might I can't seem to figure it out, any help much appreciated.
import java.util.*;
class LinkedSet<T> {
private static class Node<T> {
private T item;
private Node<T> next;
Node(T item, Node<T> next) {
this.item = item;
this.next = next;
}
}
private Node<T> head = null;
private int numItems = 0;
int size() {
return (numItems);
}
public boolean add(T t) {
if(contains(t)) return false;
Node<T> newNode = new Node(t, null); //new node to be added
if(numItems==0) {
head = newNode;
numItems++;
return true;
}
Node<T> temp = head;
while(temp.next != null) temp = temp.next;
temp.next = newNode;
numItems++;
return true;
}
public boolean remove(T t) {
if(numItems == 0) return false; //check for empty set
//was tempted to use contains here but would have made it N^2 I think
Node<T> p = head; //t if present
Node<T> pPrev = null; //previous node to p
while(p!=null && !equals(t, p.item)) {
pPrev = p;
p = p.next;
}
//t is present if node p!= null , node p != null ==> t in node p
if(p==null) return false;
else {
pPrev.next = p.next; //null pointer
numItems--;
return true;
}
}
public boolean contains(T t) {
Node<T> temp = head;
for(int i = 0; i < numItems; i++) {
if(equals(temp.item, t)) return true;
temp = temp.next;
}
return false;
}
private boolean equals(T t1, T t2) { //t1, t2 may be null
if(t1!=null) return t1.equals(t2); //learn this
else return t2 == null; //learn this
}
public static void main(String[] args) {
LinkedSet<Integer> test = new LinkedSet<Integer>();
test.add(1);
test.add(2);
test.add(3);
for(int i = 0; i < 10; i ++) {
System.out.println("Testing i = " + i + " - " + test.contains(i));
}
System.out.println(); System.out.println(); System.out.println();
System.out.println(test.remove(1));
}
}
The obvious point is that the first element in the list does not have a previous element. (Some linked list implementations will add a dummy link to handle this more cleanly.)
Look at this portion of the code:
Node<T> p = head; //t if present
Node<T> pPrev = null; //previous node to p
while(p!=null && !equals(t, p.item)) {
pPrev = p;
p = p.next;
}
If equals(t, head.item), then pPrev == null when you leave the while loop and you'll get a null pointer exception later.

Categories