How do you remove nodes from a linked list? - java

I have a linked linked of student objects. It's basically a database that stores data about students as student objects. The only problem I am having is creating the removeStudent method. Posted below is what I have tried so far, altering different parts of it to see if a different result occurs. Right now with this code, I can delete a student in my driver, but it will also delete every student before the one that I want to delete as well, leaving behind only the students that are in the database after the student that I am trying to delete.
public void RemoveElements(Object Student) {
LinearNode<Object> current = element;
LinearNode<Object> temp = current;
while (current.getNext() != null) {
temp = current;
current = current.getNext();
if(current.getElement() == Student) {
temp.setNext(current.getNext());
length--;
}
}
}

public void RemoveElements(Object Student) {
LinearNode<Object> current = element;
LinearNode<Object> previous = null;
//LinearNode<Object>(student);
while (current.getNext() != null) {
current = current.getNext();
if(current.getElement() == Student) {
length--;
element = element.getNext();
if (previous != null) {
previous.setNext(element.getNext();
} else {
//if you have a pointer to the head element place it element.getNext();
}
}
previous = current;
}
}

If the current contains the object to be removed, you need get a reference to the previous node, and point it at the next node. So you have
A -> B -> C
and B contains the item to be removed, you want your linked list to look like
A -> C
A few things are wrong with your code
1) You are not doing the above
2) You are not setting previous within your while loop. You can do that right before
current = current.getNext();
3) For the code
LinearNode<Object> current = element;
at the top, what is element?

It looks like element is the head of the list. Look at the code that changes element and change it so that when you delete the second item, element still points to the first element and the first element points to the third instead of the second.

Related

Deleting a node in a linked list with void return statement [Java]

I'm trying to a do an assignment to delete a node in a Linked list. I have the front node deletion to work, and to return when the friendList is null. firstFriend is a Friend object that has a Person in memory and points to another friend. This method removes a friend from the firstFriend linked list. I'm struggling with how to update firstFriend properly within the method
public void removeFriend(Person friend){
Friend prev = null, curr = firstFriend, front = firstFriend;
if (curr == null){
return;
}
while(firstFriend != null){
if(friend.equals(curr.who)){
if(prev == null){
firstFriend = firstFriend.nextFriend;
return;
}
else{
prev = curr.nextFriend;
}
prev = curr;
curr = curr.nextFriend;
}
firstFriend = front;
return; // replace this line
Hint #1: you only ever need to update firstFriend when you are deleting the first Friend on the list
Hint #2: separate the problem of removing a Friend into the two parts of 1) finding the Friend node that points to the Person you want to remove and 2) actually removing the Friend, instead of trying to do everything at once.

Issue with removing a node

I'm working on a link list and not currently able to remove a speficic node by a key value. I ask a helper at my school and he is not sure why it isn't working.(There is also a lot of try-catches for another issue I apologize for how gross it looks)
Here is my remove method:
public void remove(int key) throws Exception {
Node tmp = first;
Node pred = first;
while (tmp != null) {
if (tmp.keyValue == key) {
pred = tmp;
tmp = tmp.next;
} else {
tmp = tmp.next;
}
}
Here is my main method creaing the list and trying to remove it and print it:
OrderedLinkedList oLL3 = new OrderedLinkedList();
try {
oLL3.insert("Should be removed", 5);
oLL3.insert("Shouldn't be removed 2nd", 15);
oLL3.insert("Shouldn't be removed", 10);
} catch (Exception e) {
System.out.println("Error: Two nodes with the same key value and the newest one won't be stored.");
}
try {
oLL3.remove(5);
} catch (Exception r) {
System.out.println("Error:No nod with the key value to be removed");
}
System.out.print("toString test removing node: \n" + oLL3.toString());
System.out.println("Number of nodes in the List:" + oLL3.listCount());
}
In this code shown you are deleting the first node of the linked list, and to delete the first node you need to point the "head" (or whatever the name of your head node is) to the second node, i.e.
head = head.next;
Your remove method is only assigning to local variables. That is not going to affect the state in your linked list. Assuming that the head of your list is the node held by the field first, you need to assign to either first or to the .next field in another node.
To remove the first node, you can do:
first = first.next;
To remove the node after node prev, you can do:
prev.next = prev.next.next;
(null-checking where appropriate)

How to reverse LinkedList in java

Please accept my apologies first, but I could not reverse my Linked List in java..
I have class and inner class:
MyList{
class Element{
private Element next;
public Element getNext(){return next;}
}
public void reverseMyList(Element curr) {
if (curr.next == null) {
head = curr.next;
return;
}
reverseMyList(curr.next);
while (curr.next != null) {
curr.next.next = curr.next;
curr.next = null;
}
}//:~
I need to reverse my List, I am using method reverseMyList, which needs Element curr.
If my way of thinking in this case is correct ?
Thank you in advance!
Since this kinda looks like homework, I'm not going to lay out the entire solution here, but I will explain how you should conceptually do it.
Imagine that you have 2 linked lists. You have your input list that you need to reverse, and you have an empty one.
If you keep taking the first element off of the original list, and keep putting that on the front of the new list until your original list is empty, than your new list will be what the original was, except reversed.
public static void Reverse(Element element)
{
Element current = element;
Element next = current.Next;
Element nextToNext;
var first = current;
while (next != null && next.Next != null)
{
nextToNext = next.Next;
next.Next = current;
current = next;
next = nextToNext;
}
if (next != null)
{
next.Next = current;
}
first.Next = null;
}
the method you are looking for already exist in package java.utils:
Collections.reverse(mylist);
this method will change the order of element direcly inside your list and you dont need to instance a new list-object... here you can find more specified documentation

Delete last node, or only node from a Linked List in Java.

I am unable to get my program to delete the last node or only node in my linked list. It will delete any other node. This program allows the user to enter integers and delete them. Thanks in advance for your help.
// This method finds the value requested in the Linked List.
public Node find(Node head, Comparable value2){
if (head == null )
{
System.out.println("The list is empty");
return null;
}
Node pointer = head;
while (pointer != null)
{
if (pointer.data.compareTo(value2)>=0)
{
Node delNode = pointer;
System.out.print("Found it. Deleting " + delNode.data + "\n");
return delNode;
}
pointer = pointer.next;
}
return null;
}
// This method deletes a given value from the linked list.
public void delete(Node head, Comparable value2){
Node delNode;
delNode = find(head, value2);
if (delNode== null)
{
System.out.println("The value: " + value2 + " does not exist");
print(head);
}
else
{
if (delNode.next == null)
{
System.out.println("Trying to delete last");
delNode = null;
print(head);
}
else{
delNode.data = delNode.next.data;
Node temp = delNode.next.next;
delNode.next = null;
delNode.next = temp;
print(head);
}
}
return;
}
I thought that if (delNode.next== null) {delNode = null} would do it?
If you want to delete a node, you should have a reference to the node before the one you want to delete, say beforeNode, and set
beforeNode.next = beforeNode.next.next;
(Think about special cases like deleting the last element.)
See Java Linked List search and delete method
Please note that in the sequence
delNode.next = null;
delNode.next = temp;
The first line is useless.
You current delete operation effectively works by copying the next node into the current node and then deletes the next node, making it look like you deleted the current node. This is fine until there is no next node, as you have discovered.
The reason the following doesn't work
if (delNode.next == null)
{
System.out.println("Trying to delete last");
delNode = null;
print(head);
}
is that delNode is just a local variable, setting delNode to null doesn't affect anything outside of delete().
If you want to delete the last node from the list, you need to set the next pointer in the second last element to null. Therefor it is insufficient for find() to simply return the element you wish to delete -- you need the previous element.
Pseudocode for delete(data) should be (untested):
if head == null
return
if head.data == data
head = head.next
return
previous = find_previous(data)
if previous == null
return
previous.next = previous.next.next

Linked List Structure in Java

i have a question about circularly linked lists. My linked list object has two references, first and last, and the next node of the last reference is first. I want to write a method that inserts a node into the end of the list.
void insertLast(int k) {
Node a = new Node(k);
if (first == null) {
first = last = a;
} else {
last.after = a;
a.after = first;
}
last = a
}
Is something like this possible? Have I made a mistake?
Yes, it is.
let the current last point to the new one (last.setNext(newNode))
let the new one point to the first (newNode.setNext(first))
set the last to be the new node (last = newNode)

Categories