How to search and Delete in a Linked List - java

I'm having a bit trouble with a little java activity that deals with searching and deleting a Linked List.
Here are the problems:
add a menu to method main to handle adding to head, deleting from the head and displaying a linked listed.
Then add a menu selection for deleting a particular element in the list and deleting it (so prompt the user for a string to delete - and then find it in the linked list and delete that element from the list).
Here are the classes:
public class LLNode {
private String data;
private LLNode next;
public LLNode() {
this.data = null;
this.next = null;
}
public LLNode (String newData) {
this.data = (newData);
this.next = null;
}
public void updateNode (LLNode nextOne) {
this.next = nextOne;
}
public String toString () {
return this.data;
}
public LLNode getNext() {
return this.next;
}
}
public class LList {
private LLNode head;
public LList() {
head = null;
}
public void addAtHead (String newData) {
LLNode newNode = new LLNode (newData);
newNode.updateNode(head);
head = newNode;
}
public void display() {
LLNode temp = head;
while (temp != null) {
System.out.println (temp);
temp = temp.getNext();
}
}
public LLNode deleteAtHead ( ) {
LLNode removedOne = head;
head = head.getNext();
return removedOne;
}
}
public class LinkedListExample {
public static void main(String[] args) {
LList list = new LList();
list.addAtHead("Bob");
list.addAtHead("Tom");
System.out.println("The list is ");
list.display();
LLNode removedOne = list.deleteAtHead();
System.out.println("After delete, the list new is ");
list.display();
System.out.println("The one that was deleted is..." + removedOne);
}
}

For creating a menu I would recommend using a while loop. You want to use some sort of scanner that checks for valid input and checks for the input of the menu.
{
public void main(String[] args) {
string input;
Scanner n = new Scanner(System.in);
while (!(input.equals("exit")) {
System.out.println("menu item 1");
System.out.println("menu item 2");
System.out.println("etc");
input = n.nextLine();
switch (input) {
case "menu 1": //do whatever menu 1 is
case "menu 2": //do whatever menu 2 is
case "exit": //exit // save whatever
default: System.out.println("message not understood");
}
}
This is a contains method. This should give you a strong indication on how to find an element in the linkedlist and how to delete it. (I'll leave this to you, as this is relatively easy and you need to learn).
public boolean contains(String str) {
Node ref;
while (ref != null)
ref = ref.next;
if (ref.data == str) {
return true;
}
return false;
}

Related

Removing all instances of an element from a custom LinkedList

Im trying to remove all people from the list who have the same course name in my custom LinkedList class. I have managed to get my programme to delete people individually based on number however can not figure out how to remove multiple at once. I have browsed online for any solutions and have tried multiple so far but none to any success I also attempted one myself but also no success any help or links to were I could learn mode would be greatly appreciated. Below is my Driver, LinkedList, and LinearNode class. I have also removed code I beleive is not relevant to this solution :).
Linked List Class
public class LinkedList<T> implements LinkedListADT<T> {
private int count; // the current number of elements in the list
private LinearNode<T> list; //pointer to the first element
private LinearNode<T> last; //pointer to the last element
//-----------------------------------------------------------------
// Creates an empty list.
//-----------------------------------------------------------------
public LinkedList()
{
this.count = 0;
this.last = null;
this.list = null;
}
public void add (T element)
{
LinearNode<T> node = new LinearNode<T> (element);
if (size() == 0) {
this.last = node; // This is the last and the
this.list = node; // first node
this.count++;
}//end if
else
{
last.setNext(node); // add node to the end of the list
last = node; // now make this the new last node.
this.count++;
} //end else
}
public T remove()
{
LinearNode<T> current = list;
LinearNode<T> temp = list;
T result = null;
if (current == null) {
System.out.println("There are no such employees in the list");
}//end if
else {
result = this.list.getElement();
temp = list;
this.list = this.list.getNext();
temp.setNext(null); //dereference the original first element
count--;
}//end else
return result;
}
public T remove(T element)
{
LinearNode<T> current = list;
LinearNode<T> previous = list;
LinearNode<T> temp;
T result = null;
if (current == null) {
System.out.println("There are no such employees in the list");
}//end if
else {
for (current = this.list; current != null && !current.getElement().equals(element); current = current.getNext())
{
previous = current;
}
if(current == null) {
System.out.println("No such employee on the list");
}
else if (current == list)
{
remove();
}
else if(current == last) {
previous.setNext(null);
this.last = previous.getNext();
count--;
}
else
{
previous.setNext(current.getNext());
count--;
}
}
return result;
}
**
My attempted Solution**
public T clear(T element) {
T result = null;
while (this.list != null && this.list.getElement() == element) {
this.list = this.list.getNext();
count--;
}
if (this.list == null) {
return result;
}
LinearNode<T> current = this.list;
while (current.getNext() != null) {
if (current.getNext().getElement() == element) {
current.setNext(current.getNext());
count--;
} else {
current = current.getNext();
}
}
return result;
}
}
LinearNode Class
public class LinearNode<T>
{
private LinearNode<T> next;
private T element;
//---------------------------------------------------------
// Creates an empty node.
//---------------------------------------------------------
public LinearNode()
{
this.next = null;
this.element = null;
}
//---------------------------------------------------------
// Creates a node storing the specified element.
//---------------------------------------------------------
public LinearNode (T elem)
{
this.next = null;
this.element = elem;
}
//---------------------------------------------------------
// Returns the node that follows this one.
//---------------------------------------------------------
public LinearNode<T> getNext()
{
return this.next;
}
//---------------------------------------------------------
// Sets the node that follows this one.
//---------------------------------------------------------
public void setNext (LinearNode<T> node)
{
this.next = node;
}
//---------------------------------------------------------
// Returns the element stored in this node.
//---------------------------------------------------------
public T getElement()
{
return this.element;
}
//---------------------------------------------------------
// Sets the element stored in this node.
//---------------------------------------------------------
public void setElement (T elem)
{
this.element = elem;
}
}
Driver Class
public class TrainingCourses {
LinkedList<employee>list;
int Size =10;
int numberofEmployees=0;
public TrainingCourses() {
list = new LinkedList<employee>();
inputEmployee();
displayEmployee();
deleteCourses();
displayEmployee();
}
public void inputEmployee() {
employee a;
a = null;
String number,name,courseName = null;
int years;
Scanner scan = new Scanner(System.in);
for (int count = 1; count<=numberofEmployees; count++){
System.out.println("Input employee number");
number = scan.nextLine();
System.out.println("Input employee name");
name = scan.nextLine();
System.out.println("Input years at organisation");
years = scan.nextInt(); scan.nextLine();
if(years >=5) {
System.out.println("Input course name");
courseName = scan.nextLine();
}else {
System.out.println("Can not join training course employee must be with organisation 5 or more years");
}
a = new employee(number,name,years,courseName);
list.add(a);
}
}
public void displayEmployee() {
System.out.println("\nDisplaying all employees....");
System.out.println(list.toString());
}
public void deleteCourses(){
{
Scanner scan = new Scanner(System.in);
employee b = null;
String number,name,courseName;
int years;
System.out.println("Enter employee number you wish to remove");
number = scan.nextLine();
System.out.println("Input employee name");
name = scan.nextLine();
System.out.println("Input years at organisation");
years = scan.nextInt(); scan.nextLine();
System.out.println("Input course name");
courseName = scan.nextLine();
b = new employee(number,name,years,courseName);
list.clear(b);
}
}
public static void main(String[]args) {
new TrainingCourses();
}
}
I don't understand exactly what you want, because of you wrote you want "to remove all people from the list who have the same course name", but your code never checks only property, your code checks equality everywhere.
This example clear function removes all elements equals to param and returns count of removed elements.
public long clear(T element) {
long result = 0L;
LinearNode<T> current = this.list;
LinearNode<T> previous = null;
while (current != null) {
if (current.getElement().equals(element)) {
if (previous != null) {
if (current.getNext() != null) {
previous.setNext(current.getNext());
} else {
this.last = previous;
}
} else if (current.getNext() != null) {
this.list = current.getNext();
} else {
this.list = this.last = null;
}
this.count--;
result++;
} else {
previous = current;
}
current = current.getNext();
}
return result;
}
And after all .equals(..) only true, if the compared Objects has an equals() method and checks its content equality, otherwise two Objects equals by == operator, if they are exactly the same (not by there's contents).

Java - Delete Node From Linked List

Okay so this is just a simple program that will receive input from a user and add it to a linked list, and also give them the options to view the list and delete a node. It compiles fine and can add nodes and display the list but it will not delete a node. It works when I hand code it without the keyboard input, even with the same variable name so that's where the problem is.
public class LinkedList {
public class Link {
public String content;
public Link next;
public Link(String content) {
this.content = content;
}
public void display(){
System.out.println(content);
}
}
public static Link head;
LinkedList(){
head = null;
}
public boolean isEmpty() {
return(head == null);
}
public void insertFirstLink(String content) {
Link newLink = new Link(content);
newLink.next = head;
head = newLink;
}
public void display() {
Link theLink = head;
while(theLink != null) {
theLink.display();
theLink = theLink.next;
}
}
public Link removeLink(String content) {
Link curr = head;
Link prev = head;
while(curr.content != content) {
if (curr.next == null) {
return null;
}
else {
prev = curr;
curr = curr.next;
}
}
if(curr == head) {
head = head.next;
}
else {
prev.next = curr.next;
}
return curr;
}
}
public class Testlist {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int choice = 0;
String content;
System.out.println("Enter 1 to add to list");
System.out.println("Enter 2 to display list");
System.out.println("Enter 3 to delete node");
System.out.println("Enter 4 to quit");
choice = keyboard.nextInt();
LinkedList newlist = new LinkedList();
while(choice != 4) {
if (choice == 1) {
content = keyboard.next();
newlist.insertFirstLink(content);
newlist.display();
}
if (choice == 2) {
newlist.display();
}
if (choice == 3) {
content = keyboard.next(); // this is where is goes wrong
newlist.removeLink(content);
newlist.display();
}
System.out.println("Enter 1 to add to list");
System.out.println("Enter 2 to display list");
System.out.println("Enter 3 to delete node");
System.out.println("Enter 4 to quit");
choice = keyboard.nextInt();
}
}
}
You're using !=, which compares by reference for objects, not by value. You want to use .equals(), ie:
while(!curr.content.equals(content))
Some one may have to double check, but i'm fairly sure this is because the nextInt() method grabs the first integer and thats all. which leaves the 'enter/carriage return' in the input stream. so when the next() method is run it grabs that enter. Definatly put in some debug lines to see what content is.
For comparing string you should use equals or equalsignorecase()
For example String1="xyz";
and String2="xyz" these two strings are different if you comare them using == or != as the objects are compared instead of the actual content . the correct implementation for your program would be
package stackoverflow.practice;
public class LinkedList {
public class Link {
public String content;
public Link next;
public Link(String content) {
this.content = content;
}
public void display(){
System.out.println(content);
}
}
public static Link head;
LinkedList(){
head = null;
}
public boolean isEmpty() {
return(head == null);
}
public void insertFirstLink(String content) {
Link newLink = new Link(content);
newLink.next = head;
head = newLink;
}
public void display() {
Link theLink = head;
while(theLink != null) {
theLink.display();
theLink = theLink.next;
}
}
public Link removeLink(String content) {
Link curr = head;
Link prev = head;
while(!curr.content.equalsIgnoreCase(content)) {
if (curr.next == null) {
return null;
}
else {
prev = curr;
curr = curr.next;
}
}
if(curr == head) {
head = head.next;
}
else {
prev.next = curr.next;
}
return curr;
}
}
Also use 'equals' in this line: 'if(curr == head) {'.

Iterating over a linked list in Java?

I have been diligently watching YouTube videos in an effort to understand linked lists before my fall classes start and I am uncertain how to proceed with iterating over the following linked list. The 'node' class is from a series of videos (same author), but the 'main' method was written by me. Am I approaching the design of a linked list in an illogical fashion (assuming of course one does not wish to use the predefined LinkedList class since the professor will expect each of us to write our own implementation)?:
class Node
{
private String data;
private Node next;
public Node(String data, Node next)
{
this.data = data;
this.next = next;
}
public String getData()
{
return data;
}
public Node getNext()
{
return next;
}
public void setData(String d)
{
data = d;
}
public void setNext(Node n)
{
next = n;
}
public static String getThird(Node list)
{
return list.getNext().getNext().getData();
}
public static void insertSecond(Node list, String s)
{
Node temp = new Node(s, list.getNext());
list.setNext(temp);
}
public static int size(Node list)
{
int count = 0;
while (list != null)
{
count++;
list = list.getNext();
}
return count;
}
}
public class LL2
{
public static void main(String[] args)
{
Node n4 = new Node("Tom", null);
Node n3 = new Node("Caitlin", n4);
Node n2 = new Node("Bob", n3);
Node n1 = new Node("Janet", n2);
}
}
Thanks for the help,
Caitlin
There are some flaws in your linked list as stated by some of the other comments. But you got a good start there that grasps the idea of a linked list and looks functional. To answer your base question of how to loop over this particular implemention of the linked list you do this
Node currentNode = n1; // start at your first node
while(currentNode != null) {
// do logic, for now lets print the value of the node
System.out.println(currentNode.getData());
// proceed to get the next node in the chain and continue on our loop
currentNode = currentNode.getNext();
}
Maybe this will be useful:
static void iterate(Node head) {
Node current = head;
while (current != null) {
System.out.println(current.getData());
current = current.getNext();
}
}
// or through recursion
static void iterateRecursive(Node head) {
if (head != null) {
System.out.println(head.getData());
iterateRecursive(head.getNext());
}
}
class List {
Item head;
class Item {
String value; Item next;
Item ( String s ) { value = s; next = head; head = this; }
}
void print () {
for( Item cursor = head; cursor != null; cursor = cursor.next )
System.out.println ( cursor.value );
}
List () {
Item one = new Item ( "one" );
Item two = new Item ( "three" );
Item three = new Item ( "Two" );
Item four = new Item ( "four" );
}
}
public class HomeWork {
public static void main( String[] none ) { new List().print(); }
}
Good luck!!
You can have your linked list DS class implement 'Iterable' interface and override hasNext(), next() methods or create an inner class to do it for you. Take a look at below implementation:
public class SinglyLinkedList<T>{
private Node<T> head;
public SinglyLinkedList(){
head = null;
}
public void addFirst(T item){
head = new Node<T>(item, head);
}
public void addLast(T item){
if(head == null){
addFirst(item);
}
else{
Node<T> temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = new Node<T>(item, null);
}
}
private static class Node<T>{
private T data;
private Node<T> next;
public Node(T data, Node<T> next){
this.data = data;
this.next = next;
}
}
private class LinkedListIterator implements Iterator<T>{
private Node<T> nextNode;
public LinkedListIterator(){
nextNode = head;
}
#Override
public boolean hasNext() {
return (nextNode.next != null);
}
#Override
public T next() {
if(!hasNext()) throw new NoSuchElementException();
T result = nextNode.data;
nextNode = nextNode.next;
return result;
}
}
}

How to display items in a linked list in java

Hi all im wondering how to display all nodes in a linked list. Heres the code I have so far. The Manager class is supposed to operate the list. The movieNode class creates new list nodes for the movie. I know I have to use other things as well but im just trying to get the first element of the list to display for starters.
public class Manager {
MovieNode head;
public Manager (){
head=null;
}
public void Add (MovieNode data) {
if (head==null){
head=data;
}
}
public void Display () {
int i=1;
MovieNode temp=head;
System.out.println("Displaying Movies");
while (head!=null) {
System.out.println(temp.getData().getName());
head=null;
}
}
}
also, the code for the MovieNode class
public class MovieNode {
private Movie data;
private MovieNode next;
public MovieNode (){
data=null;
next=null;
}
public MovieNode (Movie data){
setData(data);
}
public void setData (Movie data){
this.data=data;
}
public Movie getData (){
return data;
}
}
Hopefully this will help you get started. Here are some pointers:
Manager Class
You don’t need an explicit constructor for Manager, as you can initialize the head variable in line and you’re not passing any other information to the constructor
Method names in Java are conventionally camel case and start with lower-case letter
When you add a new item to the linked list, you can pass in just the data and create the node in the add method
Assuming you don’t need to maintain any special order, you can insert the new item to the head of the list. This saves the time to go through the whole list to find the tail or keeping a reference to the tail.
To display all the movies, you just need to start with the head and check if there is a node next in list. If you don’t need to implement this custom method, I would recommend implementing the class as Iterable. A SO discussion on this topic can be found here
MovieNode Class
You only need one constructor that takes the data and sets the private variable
You also need the getter and setter for the next variable in order to hold the list structure and iterate through the list
The toString() implementation will allow to print an instance of this class directly, as in displayAllMovies() method
Movie Class
This class just holds the title of the movie for now, but you can extend it according to your spec.
Here is the code:
public class Manager {
MovieNode head = null;
public void addMovie(Movie data) {
MovieNode newNode = new MovieNode(data);
if (head == null) {
head = newNode;
} else {
newNode.setNext(head);
head = newNode;
}
}
public void addMovieInOrder(Movie data) {
MovieNode newNode = new MovieNode(data);
if (head == null) {
head = newNode;
} else {
MovieNode higher = head;
MovieNode lower = null;
// find the right position for newNode
while(higher != null){
if(newNode.compareTo(higher) > 0){
lower = higher;
higher = higher.getNext();
}
else break;
}
newNode.setNext(higher);
if(higher == head) head = newNode; //inserting as head
else lower.setNext(newNode);
}
}
public void displayAllMovies() {
MovieNode node = head;
if (node == null) {
System.out.println("The list is empty!");
}
do {
System.out.println(node.getData());
node = node.getNext();
} while (node != null);
}
public static void main(String[] args) {
Manager manager = new Manager();
manager.addMovieInOrder(new Movie("ddd"));
manager.addMovieInOrder(new Movie("ccc"));
manager.addMovieInOrder(new Movie("aaa"));
manager.addMovieInOrder(new Movie("bbb"));
manager.displayAllMovies();
}
}
Movie Node class:
public class MovieNode implements Comparable<MovieNode> {
private Movie data;
private MovieNode next = null;
public MovieNode(Movie data) {
this.data = data;
}
public void setData(Movie data) {
this.data = data;
}
public Movie getData() {
return data;
}
public void setNext(MovieNode node) {
this.next = node;
}
public MovieNode getNext() {
return next;
}
#Override
public String toString() {
return data.toString();
}
#Override
public int compareTo(MovieNode otherMovieNode) {
return data.compareTo(otherMovieNode.getData());
}
}
Movie class:
public class Movie implements Comparable<Movie> {
private String title;
public Movie(String title) {
this.title = title;
}
#Override
public String toString() {
return title;
}
#Override
public int compareTo(Movie otherMovie) {
return title.compareTo(otherMovie.title);
}
}

inserting data after certain data (double linklist)

Hey, so I wanted to insert one data after the input data (not index).
I've tried but it always at the end, the data that i want to insert end up at the dront of the link list..
**public static void insertAfter(Object o,Object c){
Node newN = new Node();
Node help = new Node();
Node help2 = new Node();
newN.data = o;
help = head.next;
if(isEmpty()){
head = newN;
newN.next=head;
newN.prev=head;
}
else{
do{
help=help.next;
System.out.println(help);
}while(help.next!=head || !help.data.equals(c));
help2 = help.next;
newN.next = help2;
help2.prev = newN;
help.next=newN;
newN.prev=help;
}**
anyone could help?
thx a bunch!
What are the objects that you are comparing? if they are something other than string than you will have to override equals() method in order to get the correct comparison.
I think you should try another ending condition:
while(help.next!=head && !help.data.equals(c));
By the way, I can only advise you to avoid do...while without serious reasons, and to use getters and setters.
Your code should also be structured diffently. Why are you not writing a private method which just make the insert, i.e. your 5 last lines? Everything would be more readable and reusable.
Also, your variables need clear and meaningful names.
Do it yourself
I begun fixing your solution but ended writing a whole new implementation when wanting to test it... so here goes:
public class DoubleLinkedList<T> {
private class Node {
private Node prev;
private Node next;
private T data;
Node(T data) {
this.data = data;
}
}
Node head;
public boolean isEmpty() {
return head == null;
}
public void insertAfter(T afterThis, T objectToAdd) {
// cannot insert after in a empty list?!
if(isEmpty())
throw new NoSuchElementException("list is empty?");
// find the node where we want to insert the element
Node after = findNodeByObject(afterThis);
// create the node and update the links
addAfter(after, new Node(objectToAdd));
}
private void add(T objectToAdd) {
if (isEmpty()) {
head = new Node(objectToAdd);
head.next = head;
head.prev = head;
}
else {
addAfter(head.prev, new Node(objectToAdd));
}
}
private void addAfter(Node after, Node toAdd) {
Node afterAfter = after.next;
after.next = toAdd;
afterAfter.prev = toAdd;
toAdd.prev = after;
toAdd.next = afterAfter;
}
private Node findNodeByObject(T object) {
Node current = head;
while (true) {
if (current.data.equals(object))
return current;
if (current.next == head)
break;
current = current.next;
}
throw new NoSuchElementException("" + object);
}
#Override
public String toString() {
List<T> printList = new LinkedList<T>();
Node current = head;
while (true) {
printList.add(current.data);
if (current.next == head)
break;
current = current.next;
}
return printList.toString();
}
public static void main(String[] args) throws Exception {
DoubleLinkedList<String> list = new DoubleLinkedList<String>();
list.add("first");
list.add("third");
list.insertAfter("first", "second");
System.out.println(list);
}
}
Extend LinkedList
... and add the insertAfter method like this:
import java.util.LinkedList;
import java.util.ListIterator;
public class MyList<T> extends LinkedList<T> {
private void insertAfter(T first, T second) {
ListIterator<T> iterator = listIterator();
while (iterator.hasNext()) {
if (iterator.next().equals(first)) {
iterator.add(second);
return;
}
}
throw new IndexOutOfBoundsException("Could not find " + first);
}
public static void main(String[] args) throws Exception {
MyList<String> list = new MyList<String>();
list.add("first");
list.add("third");
list.insertAfter("first", "second");
System.out.println(list); // prints "[first, second, third]"
}
}

Categories

Resources