Linked List Java adding elements - java

I am learning linked lists in java and I have problem with the first element that is being enrolled twice. How to fix this problem. Here is my code :
if (head==null) {
head=new Node(data);
}
Node current=head;
while(current.getNext()!=null) {
current=current.getNext();
}
current.setNext(new Node(data));// how to change this line
}
https://pastebin.com/2PCvJmKT

You should add return, after adding first element.
if (head==null) {
head = new Node(data);
return;
}
I took code from link.

In pastebin, this code snippet is a part of your "insert"-function.
So in the code snippet you're looking upon the case "What if my LinkedList is empty? -> no elements in list -> no head
If that's the case, you just want to add the new data into the empty List as an new Node(data).
But what you're doing right now is: You're creating a new Node for an empty list, set that Node as Head and iterating through a list with just one element. That practically means, that you will never enter your while loop. After that you're adding a Node with the same data as the Head as its successor.

Related

Reversing a singly linked list [Java]

I was wondering if someone could help explain how to reverse a singly linked list without creating new nodes or changing data in the existing nodes. I am trying to study for finals and we had this question on a previous test. They don't release answers to the coding portions of the test and I haven't been able to figure it out.
They told us the best way to reverse it was by using a "runner technique" which I believe I understand what that is. They described it as using two pointers or counters to run through a list and gather information but I'm not sure how to use that to reverse a singly liked list. I was able to brute-force code to reverse a list of length 2, 3, and 4 but I was unable to make a loop or do it recursively. Any code or an explanation on how to go about this would be appreciated, thank you.
You can derive the code by starting with the idea of merely - one by one - popping elements off the input list and pushing them onto an initially empty result list:
NODE reverse(NODE list) {
NODE result = null;
while (list != null) {
NODE head = <pop the first node off list>
<push head onto result>
}
return result;
}
The result will be the reverse of the input. Now substitute Java for the missing pieces
NODE reverse(NODE list) {
NODE result = null;
while (list != null) {
// pop
NODE head = list;
list = list.next;
// push
head.next = result;
result = head;
}
return result;
}
And you're done...
It depends on your implementation of the list, but I would recurse to the end and then reverse the references.
void Reverse(List pList) {
Reverse(pList, null, pList.First); // initial call
}
void Reverse(List pList, Node pPrevious, Node pCurrent) {
if (pCurrent != null)
Reverse(pList, pCurrent, pCurrent.Next); // advance to the end
else { // once we get to the end, make the last element the first element
pList.First = pPrevious;
return;
}
pCurrent.Next = pPrevious; // reverse the references on all nodes
}

Removing duplicate element from a linked list- Java

EDIT
I decided to use a HashSet instead as it has is O(N). However, I am still having an issue that it's not deleting all repeating numbers, 10 13 11 11 12 11 10 12 11.
It returns : 10 13 11 12 10 11
static void removeDups(Node node) {
HashSet<Integer> values = new HashSet<Integer>();
Node previous = null;
while(node != null) {
if(values.contains(node.data))
previous.next = node.next;
else
values.add(node.data);
previous = node;
node= node.next;
}
}
Irrelevant
I am trying to remove duplicate elements from a linked list but for some reason, It does not remove the last repeating element. For instance if the list is 10,11,12,11,12,9,11, It returns : 10,11,12,9,11.
public static void removeDups1(Node head){
if(head == head.next)
head = head.next.next;
Node fastptr =head;
Node slowptr = head;
while(slowptr.next != null && fastptr.next.next !=null) {
if(slowptr.data == fastptr.data) {
fastptr.next = fastptr.next.next;}
slowptr = slowptr.next;
fastptr = fastptr.next;
}}
Checking fastptr.next.next == null prematurely exits your loop.
Your algorithm is trying to find if there are any duplicates for each element from the current position to the next two positions in the linked list. But duplicates can occur anywhere in the linked list. Therefore, for each element, it should traverse through the linked list once again.
That would be a O(n^2) solution
A better approach would be to maintain a hash to keep track of already visited data.
This would be a O(n) solution.
I think, since at the beginning you are pointing both fastptr and slowptr to the same Node, and always end up pointing them to the same node at the end of the while, you're always comparing the same Nodes here, doing nothing valuable to the algorithm:
if(slowptr.data == fastptr.data)
Anyways, the algorightm's logic seems all wrong.
Like others sayd, you should do two loops, one inside another: the first one to the slowptr, the second one to the fastptr
Try to implement based on this proposition:
For all Node (pointed by slowptr, first loop), for all subsequent nodes (second loop) do see if they are the same.
I don't see real Java when I look to your code. But anyway as #Aishwarya said a better solution is to build a map or hash set for better performance. Using Java built-in functions it is even simpler. Just do:
LinkedList<Node> yourList = ...
LinkedList<Node> filteredList = new LinkedList<>(new HashSet<Node>(yourList));
To make this work properly you must make sure that Node equals(Object o) and hashCode()are correctly implemented.
Then your (generic) duplicate removal function might be:
public static void removeDups(LinkedList pList) {
return new LinkedList(new HashSet(pList));
// indeed specifying <Node> is not really needed
}

Linked List removing duplicate from list, reference confusion

I'm having trouble understanding how this method below removes the duplicates in the linked list. After calling this method, all duplicates are successfully removed. Why is the head not null? Wouldnt the head node be null because the current variable in the method iterated to the end. How does this method successfully update the list to get rid of the duplicate items?
static void removeDuplicate(node head)
{
// Hash to store seen values
HashSet<Integer> hs = new HashSet<>();
node current = head;
node prev = null;
while (current != null)
{
int curval = current.val;
// If current value is seen before
if (hs.contains(curval)) {
prev.next = current.next;
} else {
hs.add(curval);
prev = current;
}
current = current.next;
}
}
Elements get removed by changing the pointer from the previous element to point to the next element. That is how you remove elements in LinkedLists, by skipping them. The garbage collector will later remove the object as no object refers to it anymore.
Here is an illustration of the removal:
Duplicates are identified by memorizing each encountered value in a HashSet. If you find an element which was already encountered before (i.e. contained in the set), it is a duplicate.
The head can not get null because it was not null previously and duplicates can only occur after the first element, since you need to encounter an element at least once until you can find a duplicate. For example a list like [1, 1, 1] gets modified to [1] and not to [].
Also the variable head gets not changed in the method, it points to the head-node before and after the method. It seems that you got confused by current = head but you need to know that this, in Java, does not synchronize both variables. If the method changes current this changes are not reflected by head. The statement just means 'let current point to where head points' and afterwards you let current point elsewhere.

Subtracting a passed Linked List in the Method from the Calling Linked List

Essentially what this problem does is take in a Linked List as a parameter and subtracts its contents from the calling Linked List if the same contents exist in both. I have to do it this way (so no changing the parameters).
For instance: l1.subtractList(l2) would subtract the contents of l2 from l1.
The trouble here is that the calling Linked List has 2 of the same number and that number is also in the Linked List passed as a parameter. I only have to remove one instance of it as well.
I've managed to subtract everything but that duplicate number, but I'm not sure what I'm doing wrong. Keep in mind this is a very new subject to me, so I may be way off base. But I appreciate any and all help you may offer. Thanks.
public void subtractList(LinkedList list)
{
Node current = head;
Node<Integer> temp = list.getFirst();
Integer count = -1;
while (current != null)
if (current == temp){
count++;
list.listRemove(count);
temp = list.getFirst();
}
else
{
current = current.getNext();
}
}
What is listRemove method? Why do you need count? Just traverse the argument list and check if its element temp exists in the calling Linked List. You will need an outer loop traversing the list passed as argument and an inner loop iterating over the calling list to check the value of the element needing to be removed and to remove it if required
while(temp!=null)
{
while(current!=null){
//Check if element exists in list
//If yes, remove it from the calling list
}
//Repeat
temp = temp.getNext();
}

Reversing a doubly linked list in Java without creating new list

I'm trying to reverse a doubly linked list in Java and can't seem to figure out why I am getting NullPointer errors. I know that there are other questions on here which deal with the same topic such as
Reversing a Doubly Linked List
Reversing a linked list
and a few others that I have found.
I am sorry for the duplicate but I think what I am doing is the same as what the answers advise and I can't seem to figure out why my function isn't working.
I know that I need to traverse the list and swap the pointers for next and previous until I reach the end of the list, which should result in the list being reversed.
Here is the code for my function:
public void reverse() {
Node<AnyType> temp = null;
//Start at the beginning of the list
Node<AnyType> current = beginMarker;
//Go until the end of the list is reached
while (current != null)
{
//Update temp to remember what came before the current node
temp = current.prev;
//Then switch the previous and next pointers
current.prev = current.next;
current.next = temp;
//Advance current to point to the next node in the list, which is now
//stored in current.prev
current = current.prev;
}
}
and this is what I think I am doing:
Creating a temp variable to hold the value of the next the previous value for when I make a swap, initially set to null because the last node should have a pointer to null for node.next, and a current variable to hold where I am currently in the list.
Then while current is not null, so while I am not at the end of the list, I am setting the temp variable to what came before current. Then I'm swapping the pointers for previous and next, and setting the new value of current to current.prev, which should move me forward a node in the list.
However there must be something that I am missing here. I would appreciate being pushed in the right direction.
Edit:
This is my stack trace but it is not giving me an error within the function so I'm not sure how exactly to read it to find where the issue is
Exception in thread "main" java.lang.NullPointerException
at MyLinkedList$LinkedListIterator.next(MyLinkedList.java:285)
at MyLinkedList.toString(MyLinkedList.java:186)
at java.lang.String.valueOf(String.java:2847)
at java.io.PrintStream.println(PrintStream.java:821)
at MyLinkedList.main(MyLinkedList.java:321)

Categories

Resources