How to delete a specific node in a linked list - java

I previously needed help debugging my deleteNode method. It works now (updated version posted below) but I want it to provide for the case when it has to delete the head node. At the moment, it returns a NullPointerException where I've inserted * in deleteNode. I don't know how any of my variables can be null at that point, seeing as my while loop requires both position and head to not be null in the first place.
public class LinkedList
{
private class Node
{
int item;
Node link;
#SuppressWarnings("unused")
public Node()
{
item = Integer.MIN_VALUE;
link = null;
}
public Node(int x, Node p)
{
item = x;
link = p;
}
}
private Node head;
public LinkedList()
{
head = null;
}
public boolean deleteNode (int target)
{
Node position = head;
boolean isGone = false;
while(position != null && head != null)
{
if(position.link == head && position.link.item == target)
{
head = head.link;
isGone = true;
return isGone;
}
*** else if(position.link.item == target && position.link != head)
{
position.link = position.link.link;
isGone = true;
return isGone;
}
position = position.link;
}
return isGone;
}
public void printList()
{
System.out.println("Your list is: ");
Node position = head;
while(position != null)
{
System.out.println(position.item + " ");
position = position.link;
}
System.out.println();
}
}

LinkedList.deleteNode(int) never modifies any node's link, so it doesn't remove any element from the list.
Suppose that nodeA.link == nodeB, and nodeB.item == target. Then you need to set nodeA.link = nodeB.link, so that nothing is pointing to nodeB anymore.

Here is a list of the problems I see:
The enumerator you actually want to use, position, is never updated. The enumerator that is updated, counter is not needed.
You are never actually removing the node. In order to remove the node, you need to set the previous node's link to the matching node's link, thus removing it out of the chain.
You aren't dealing with special cases. What happens if the list passed is null? What happens if the matching node is the first node? The last node?
You should be returning the head of the linked list from the calling function. This is required for when removing the head node of the linked list.
Since this is a homework question, try to work it out for yourself but hopefully those points will help.

Look at your deleteNode() while loop code.
while(position != null && counter != null)
{
itemAtPosition = position.item;
if(itemAtPosition == target)
{
position = position.link;
isGone = true;
}
counter = counter.link;
}
you update counter, but never refer to it. position never changes, so the
if(itemAtPosition == target)
line never returns true. I suspect somewhere you need to check on counter.item!

First, you didn't write code for the case where the target item is located at the beginning, in which the field head should be updated accordingly. Second, the compared item is never updated during traversing the list.

Related

Swapping Nodes into Ascending Order

I have a method that adds elements into a doubly linked list, and swaps elements into ascending order if the first element is greater than the second element. If I input 23, 24, 16, it skips swapping 23 and 24 because those are good, and then it swaps 23 and 16 fine. Then when it goes back into the for loop I get an error saying that first.getNext() is null. I can see that next is getting lost in the swapping, and I tried wrestling with some fixes but have not been able to get it right.
#Override
public void add(T element) throws NullPointerException{
DoubleLinearNode<T> newNode = new DoubleLinearNode<T>(element); // Calls constructor to create a new node with data set to parameter.
if(element == null)
throw new NullPointerException("Cannot add a null element"); // Throws exception when parameter is null.
if(isEmpty()) { // Add a single node.
head = newNode;
tail = newNode;
count++;
modChange++;
}
else { // Add node to the back.
tail.setNext(newNode);
newNode.setPrevious(tail);
tail = newNode;
count++;
modChange++;
}
//}
DoubleLinearNode<T> hold = null;
DoubleLinearNode<T> first = null; // First element in list.
DoubleLinearNode<T> second = null; // Second element in list.
if(size() > 1) { // If there are 2 elements to compare then swap.
for(first = head; first.getNext() != null; first = first.getNext()) {
for(second = first.getNext(); second != null; second = second.getNext()) {
if(first.getData().compareTo(second.getData()) > 0) {
hold = first;
first = second;
second = hold;
System.out.println(first.getData());
System.out.println(second.getData());
}
}
}
}
}
I tried using this code to swap nodes but then I get an error saying that hold is null.
hold.setData(first.getData());
first.setData(second.getData());
second.setData(hold.getData());
Something like this might work. As mentioned in the comments, you do not need to swap, just find the insertion point and relink from both sides:
#Override
public void add(T element) {
DoubleLinearNode<T> newNode = new DoubleLinearNode<>(element);
if (element == null)
throw new UnsupportedOperationException("Cannot add a null element");
//Add first node
if (isEmpty()) {
head = newNode;
tail = newNode;
} else {
//I would suggest to extract the following logic to
// a dedicated methods to find the insertion point and another to do the insertion
//The head needs to be replaced
if (head.getData().compareTo(newNode.getData()) > 0) {
newNode.setNext(head);
head.setPrevious(newNode);
head = newNode;
} else {
DoubleLinearNode<T> node = head.getNext();
while (node != null) {
if (node.getData().compareTo(newNode.getData()) > 0) {
DoubleLinearNode<T> previous = node.getPrevious();
newNode.setNext(node);
node.setPrevious(newNode);
previous.setNext(newNode);
newNode.setPrevious(previous);
break;
}
node = node.getNext();
}
//If no insertion point found add it to the tail
if (node == null) {
tail.setNext(newNode);
newNode.setPrevious(tail);
tail = newNode;
}
}
}
count++;
modChange++;
}
Few more notes, throws NullPointerException it's not needed at all. It is a runtime exception. It's also incorrectly used, you should throw UnsupportedOperationException or IllegalArgumentException in such cases. But is it really needed to throw an exception? It's a bad practice to control the program flow by exceptions. If I was implementing this, I would maybe just do nothing in case of null element or change the method add to return a boolean indicating whether the addition was successful or not and return false in case of null element.
You used for loops where while loop is a better fit, it works with for loop as well, but it's less readable.

How to rearrange elements in a LinkedList so that negative numbers come first? And it successfully ends the loop?

I am a beginner, below is the best that I could come up so far. The objective of the method .Split() is that I am supposed to rearrange (rearrange only, no adding or removing nodes nor switching data of the nodes) the elements of the LinkedIntList <- This is not that standard LinkedList class, its a modified class that I have to use, there is no Java method that I can use for this problem unfortunately.
For example, if a linkedlist is [1, 5, -9, 7, -5, 78], the result should be [-9,-5, 1, 5, 7, 78]. The order of the negative values do not matter.
There is only one private field, which is ListNode front;
I am trying to use current.data < 0 to pick out the negative values and put them at the front of the list, iterating from the front, and start over. Making sure that it selects all the negative values from the list. But my output keeps getting stuck in a endless loop, unable to break. I am not sure what to do here.
Here is my best attempt at this problem.
public void Split()
{
ListNode current = front;
ListNode head = front;
while (current.next != null)
{
if (current.data < 0)
{
current.next = front; // set the pointer of current's node
front = current; // update the head with a negative value
current = current.next; // iterate from the front
}
else if (current.data >= 0)
{
current = current.next; // if positive, skip the process and keep iterating
}
else
{
break; // break if null or anything else
}
if (current.next == null || current == null)
{
break; // another attempt to break since it keeps getting stuck
}
}
}
hi llda: in order to move negative numbers ahead, I suggest get it done via two adjacent pointers. See the demo idea picture attached.
The code shows below:
public void Split(){
ListNode current = front.next;
ListNode prior = front;
ListNode head = front;
do {
if(current.data < 0 && current.next != null){
prior.next = current.next;
head = current;
head.next = front;
current = prior.next;
}
current = current.next;
prior = prior.next;
} while(current.next != null)
}
You have to update all related references to keep the linked list intact.
As a homemade implementation, I would suggest a full sort (a kind of bubblesort) this way:
...
public void sort() {
ListNode item = front;
while (item.next != null) {
if (needSwapping(item, item.next)) {
item = swapItems(item, item.next);
if (item.prev != null) {
// one step back to check next against prev in next loop
item = item.prev;
}
} else {
item = item.next;
}
}
front = firstNode(item);
}
private ListNode swapItems(ListNode item, ListNode next) {
ListNode outerPrev = item.prev;
ListNode outerNext = next.next;
// change the refs of outer elements
if (outerPrev != null) {
outerPrev.next = next;
}
if (outerNext != null) {
outerNext.prev = item;
}
// change refs to outer elements
item.next = next.next;
next.prev = item.prev;
// change inner refs
item.prev = next;
next.next = item;
return next;
}
private boolean needSwapping(ListNode item, ListNode next) {
return item.data > next.data;
// here is the point for optimizations of sort accuracy eg. negatives order doesn't matter
// return item.data >0 && item.data > next.data;
}
...
But much more modern Java Style would be to implement the Comparable interface or to provide a Comparator and make use of the Collections.sort method as described here or at stackoverflow.

Linked List Delete Method

The following is a class definition for my Linked List. I run a test program that creates a new LinkedList and inserts the numbers "3, 2, 1" and then prints the list. This works fine. However, when I try and delete "3" or "2," the delete method never completes. When I try and delete "1," it just prints out the complete list as if nothing had been deleted.
public class LinkedListTest implements LinkedList {
private Node head;
public LinkedListTest(){
head = new Node();
}
public void insert(Object x){
if (lookup(x).equals(false)){
if (head.data == null)
head.data = x;
else{
//InsertLast
Node temp = head;
while (temp.next != null){
temp = temp.next;
}
Node NewNode = new Node();
NewNode.data = x;
NewNode.next = null;
temp.next = NewNode;
}
}
//Runtime of insert method will be n, where n is the number of nodes
}
public void delete(Object x){
if (lookup(x).equals(true)){
if (head.data == x)
head = head.next;
else{
Node temp = head;
while (temp.next != null){
if ((temp.next).data == x)
temp.next = (temp.next).next;
else
temp = temp.next;
}
}
}
}
public Object lookup(Object x){
Node temp = head;
Boolean search = false;
if (head.data == x)
search = true;
while (temp.next != null){
if (temp.data == x){
search = true;
}
else{
temp = temp.next;
}
}
return search;
}
public boolean isEmpty(){
if (head.next == null && head.data == null)
return true;
else
return false;
}
public void printList(){
Node temp = head;
System.out.print(temp.data + " ");
while (temp.next != null){
temp = temp.next;
System.out.print(temp.data + " ");
}
}
}
EDIT: Here is the node class:
public class Node {
public Object data;
public Node next;
public Node(){
this.data = null;
this.next = null;
}
}
There are a few issues here.
The first big issue is that in your lookup() and your delete() methods, you don't break out of your loops when a successful condition occurs. This is why your program is hanging; it's in an infinite loop.
It's also worth noting a this point is that it's an incredibly bad practice not to use curly braces with all if/else statements. There's no reason not to do so, and it can introduce bugs easily when you don't.
in lookup() you should have:
if (head.data == x) {
search = true;
} else {
while (temp.next != null){
if (temp.data == x){
search = true;
break;
} else {
temp = temp.next;
}
}
}
and in delete():
if (head.data == x) {
head = head.next;
} else {
Node temp = head;
while (temp.next != null) {
if (temp.next.data.equals(x)) {
temp.next = temp.next.next;
break;
} else {
temp = temp.next;
}
}
}
Now this will produce what you expect:
public static void main( String[] args )
{
LinkedListTest llt = new LinkedListTest();
llt.insert(1);
llt.insert(2);
llt.insert(3);
llt.printList();
System.out.println();
llt.delete(2);
llt.printList();
}
Output:
1 2 3
1 3
However, that doesn't expose your second, larger issue. You're comparing reference values using == when looking at the node's data.
This "works" at the moment because of a side-effect of auto-boxing small integer values; you're getting the same object references. (String literals would also "work" because of the string pool). For more info on this, look at How do I compare Strings in Java and When comparing two integers in java does auto-unboxing occur
Let's look at this:
public static void main( String[] args )
{
LinkedListTest llt = new LinkedListTest();
llt.insert(1000);
llt.insert(2000);
llt.insert(2000);
llt.insert(3000);
llt.printList();
System.out.println();
llt.delete(2000);
llt.printList();
}
Output:
1000 2000 2000 3000
1000 2000 2000 3000
lookup() stopped working, allowing a duplicate to be inserted. delete() stopped working as well.
This is because int values over 127 auto-box to unique Integer objects rather than cached ones (see the linked SO question above for a full explanation).
Anywhere you're using == to compare the value held by data needs to be changed to use .equals() instead.
if (temp.data.equals(x)) {
With those technical issues solved, your program will work. There's other things that you should consider though. The two that jump right out are:
lookup should return a boolean.
There's no need to call lookup() in delete()
lookup itself is a fairly inefficient approach as a separate method; An insert iterates through the entire list twice.
First of all why does lookup return an object? change it to boolean.
also your "while" loop in lookup() doesn't advance. you need to remove the "else".
your delete function seems fine though.
I think you got quite some things wrong.
First of all, when you use LinkedList all of the functionality you tried to implement already exists.
Furthermore your style is relatively bad. For example, why do you use the WrapperClass Boolean for lookup?
Combining functionality like contains with something like get in one method is not a good idea. Split this up in two methods, let contains just return a boolean and test if an element exists in the list. Let get search and return for an element.
In addition to this you try to compare the Objects via equal. If you have not overwritten equals you can not delete anything ever, because equals needs reference equality which is not given most times.
I would highly recommend that you buy a java book or something to improve your overall knowledge..

Using references (temporary variables) to manipulate LinkedList?

public void deleteItem(int target)
{
int index = 0;
CarNode item = head;
while(item != null)
{
CarNode next = (item.node).node;
CarNode previous = item;
if (index == target)
{
previous.setNode(next);
}
item = element.node
index++;
}
}
Yeah, I don't know if I understood well, but I got told that you can use reference and don't have to directly refer to an object of the linked list in order to perform changes on the linked list.
A node contains the Car object and the node of another element of the LinkedList, right, so the reference is basically a clone that points to the same object as the original, but how come that the original is ignored and the reference takes precedence over the original when we modify the node of the reference? Sorry, it didn't make any sense to me and I've been scratching my head for hours over this.
The code should look like this:
public void deleteItem(int target)
{
int index = 0;
CarNode item = head;
CarNode prev = null;
while(item != null)
{
if (index == target) {
if (prev == null) {
head = item.getNode();
return; // We've removed the target.
} else {
prev.setNode(item.getNode());
return; // We've removed the target.
}
}
prev = item;
item = item.getNode();
index++;
}
}
So let's break this down:
int index = 0;
CarNode item = head;
CarNode prev = null;
We need two variables: one to store the element we're looking at, the other to store the previous element (which we will use to reconnect the list once we remove an element). To start, our current is the head, and our previous doesn't exist. index will let us know when we reach the target.
while(item != null)
We want to iterate until we've hit the end of the list, marked by a null node.
if (index == target) {
if (prev == null) {
head = item.getNode();
return; // We've removed the target.
} else {
prev.setNode(item.getNode());
return; // We've removed the target.
}
}
If we've found the target, we remove it. If previous is null, then the target was the head, so we move the head to the 2nd element. Otherwise, we make the previous node's reference to be the current node's reference, which cuts the current node out of the list. Once we remove the target, we are done, so we return.
prev = item;
item = item.getNode();
index++;
Update the previous and current nodes. Both are moved forward one node. Index is incremented.
How about an illustrated example:
Take a list of size 3. It looks like this:
We now call list.deleteItem(1); This instantiates a prev and a next node. next points to the first node, and prev is null.
Our target is 1, so we move to the next node. Now prev points to what next used to point to, and next points to the 2nd object in the list (the one we want to remove).
We remove it by setting the prev node's reference to be the next node's reference.
When we return from the method, java garbage collection does its job, and we're left with:
Tada! Node removed from the list!
public void deleteItem(int target)
{
int index = 0;
CarNode item = head;
CarNode next = null;
CarNode previous = null;
// stop when the linked-list ends
while(item != null)
{
// the tail has no next node
if (item.node != null)
next = item.node.node;
else
next = null;
// if targetIndex exist, remove it
// "logically" from the linekd-list
if (index == target)
{
previous.setNode(next);
break;
}
// today is tomorrow's yesterday
previous = item;
item = item.node;
index++;
}
}

How to detect a loop in a linked list?

Say you have a linked list structure in Java. It's made up of Nodes:
class Node {
Node next;
// some user data
}
and each Node points to the next node, except for the last Node, which has null for next. Say there is a possibility that the list can contain a loop - i.e. the final Node, instead of having a null, has a reference to one of the nodes in the list which came before it.
What's the best way of writing
boolean hasLoop(Node first)
which would return true if the given Node is the first of a list with a loop, and false otherwise? How could you write so that it takes a constant amount of space and a reasonable amount of time?
Here's a picture of what a list with a loop looks like:
You can make use of Floyd's cycle-finding algorithm, also known as tortoise and hare algorithm.
The idea is to have two references to the list and move them at different speeds. Move one forward by 1 node and the other by 2 nodes.
If the linked list has a loop they
will definitely meet.
Else either of
the two references(or their next)
will become null.
Java function implementing the algorithm:
boolean hasLoop(Node first) {
if(first == null) // list does not exist..so no loop either
return false;
Node slow, fast; // create two references.
slow = fast = first; // make both refer to the start of the list
while(true) {
slow = slow.next; // 1 hop
if(fast.next != null)
fast = fast.next.next; // 2 hops
else
return false; // next node null => no loop
if(slow == null || fast == null) // if either hits null..no loop
return false;
if(slow == fast) // if the two ever meet...we must have a loop
return true;
}
}
Here's a refinement of the Fast/Slow solution, which correctly handles odd length lists and improves clarity.
boolean hasLoop(Node first) {
Node slow = first;
Node fast = first;
while(fast != null && fast.next != null) {
slow = slow.next; // 1 hop
fast = fast.next.next; // 2 hops
if(slow == fast) // fast caught up to slow, so there is a loop
return true;
}
return false; // fast reached null, so the list terminates
}
Better than Floyd's algorithm
Richard Brent described an alternative cycle detection algorithm, which is pretty much like the hare and the tortoise [Floyd's cycle] except that, the slow node here doesn't move, but is later "teleported" to the position of the fast node at fixed intervals.
The description is available at Brent's Cycle Detection Algorithm (The Teleporting Turtle). Brent claims that his algorithm is 24 to 36% faster than the Floyd's cycle algorithm.
O(n) time complexity, O(1) space complexity.
public static boolean hasLoop(Node root) {
if (root == null) return false;
Node slow = root, fast = root;
int taken = 0, limit = 2;
while (fast.next != null) {
fast = fast.next;
taken++;
if (slow == fast) return true;
if (taken == limit) {
taken = 0;
limit <<= 1; // equivalent to limit *= 2;
slow = fast; // teleporting the turtle (to the hare's position)
}
}
return false;
}
An alternative solution to the Turtle and Rabbit, not quite as nice, as I temporarily change the list:
The idea is to walk the list, and reverse it as you go. Then, when you first reach a node that has already been visited, its next pointer will point "backwards", causing the iteration to proceed towards first again, where it terminates.
Node prev = null;
Node cur = first;
while (cur != null) {
Node next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
boolean hasCycle = prev == first && first != null && first.next != null;
// reconstruct the list
cur = prev;
prev = null;
while (cur != null) {
Node next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return hasCycle;
Test code:
static void assertSameOrder(Node[] nodes) {
for (int i = 0; i < nodes.length - 1; i++) {
assert nodes[i].next == nodes[i + 1];
}
}
public static void main(String[] args) {
Node[] nodes = new Node[100];
for (int i = 0; i < nodes.length; i++) {
nodes[i] = new Node();
}
for (int i = 0; i < nodes.length - 1; i++) {
nodes[i].next = nodes[i + 1];
}
Node first = nodes[0];
Node max = nodes[nodes.length - 1];
max.next = null;
assert !hasCycle(first);
assertSameOrder(nodes);
max.next = first;
assert hasCycle(first);
assertSameOrder(nodes);
max.next = max;
assert hasCycle(first);
assertSameOrder(nodes);
max.next = nodes[50];
assert hasCycle(first);
assertSameOrder(nodes);
}
Tortoise and hare
Take a look at Pollard's rho algorithm. It's not quite the same problem, but maybe you'll understand the logic from it, and apply it for linked lists.
(if you're lazy, you can just check out cycle detection -- check the part about the tortoise and hare.)
This only requires linear time, and 2 extra pointers.
In Java:
boolean hasLoop( Node first ) {
if ( first == null ) return false;
Node turtle = first;
Node hare = first;
while ( hare.next != null && hare.next.next != null ) {
turtle = turtle.next;
hare = hare.next.next;
if ( turtle == hare ) return true;
}
return false;
}
(Most of the solution do not check for both next and next.next for nulls. Also, since the turtle is always behind, you don't have to check it for null -- the hare did that already.)
In this context, there are loads to textual materials everywhere. I just wanted to post a diagrammatic representation that really helped me to grasp the concept.
When fast and slow meet at point p,
Distance travelled by fast = a+b+c+b = a+2b+c
Distance travelled by slow = a+b
Since the fast is 2 times faster than the slow.
So a+2b+c = 2(a+b), then we get a=c.
So when another slow pointer runs again from head to q, at the same time, fast pointer will run from p to q, so they meet at the point q together.
public ListNode detectCycle(ListNode head) {
if(head == null || head.next==null)
return null;
ListNode slow = head;
ListNode fast = head;
while (fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
/*
if the 2 pointers meet, then the
dist from the meeting pt to start of loop
equals
dist from head to start of loop
*/
if (fast == slow){ //loop found
slow = head;
while(slow != fast){
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
The user unicornaddict has a nice algorithm above, but unfortunately it contains a bug for non-loopy lists of odd length >= 3. The problem is that fast can get "stuck" just before the end of the list, slow catches up to it, and a loop is (wrongly) detected.
Here's the corrected algorithm.
static boolean hasLoop(Node first) {
if(first == null) // list does not exist..so no loop either.
return false;
Node slow, fast; // create two references.
slow = fast = first; // make both refer to the start of the list.
while(true) {
slow = slow.next; // 1 hop.
if(fast.next == null)
fast = null;
else
fast = fast.next.next; // 2 hops.
if(fast == null) // if fast hits null..no loop.
return false;
if(slow == fast) // if the two ever meet...we must have a loop.
return true;
}
}
Algorithm
public static boolean hasCycle (LinkedList<Node> list)
{
HashSet<Node> visited = new HashSet<Node>();
for (Node n : list)
{
visited.add(n);
if (visited.contains(n.next))
{
return true;
}
}
return false;
}
Complexity
Time ~ O(n)
Space ~ O(n)
The following may not be the best method--it is O(n^2). However, it should serve to get the job done (eventually).
count_of_elements_so_far = 0;
for (each element in linked list)
{
search for current element in first <count_of_elements_so_far>
if found, then you have a loop
else,count_of_elements_so_far++;
}
public boolean hasLoop(Node start){
TreeSet<Node> set = new TreeSet<Node>();
Node lookingAt = start;
while (lookingAt.peek() != null){
lookingAt = lookingAt.next;
if (set.contains(lookingAt){
return false;
} else {
set.put(lookingAt);
}
return true;
}
// Inside our Node class:
public Node peek(){
return this.next;
}
Forgive me my ignorance (I'm still fairly new to Java and programming), but why wouldn't the above work?
I guess this doesn't solve the constant space issue... but it does at least get there in a reasonable time, correct? It will only take the space of the linked list plus the space of a set with n elements (where n is the number of elements in the linked list, or the number of elements until it reaches a loop). And for time, worst-case analysis, I think, would suggest O(nlog(n)). SortedSet look-ups for contains() are log(n) (check the javadoc, but I'm pretty sure TreeSet's underlying structure is TreeMap, whose in turn is a red-black tree), and in the worst case (no loops, or loop at very end), it will have to do n look-ups.
If we're allowed to embed the class Node, I would solve the problem as I've implemented it below. hasLoop() runs in O(n) time, and takes only the space of counter. Does this seem like an appropriate solution? Or is there a way to do it without embedding Node? (Obviously, in a real implementation there would be more methods, like RemoveNode(Node n), etc.)
public class LinkedNodeList {
Node first;
Int count;
LinkedNodeList(){
first = null;
count = 0;
}
LinkedNodeList(Node n){
if (n.next != null){
throw new error("must start with single node!");
} else {
first = n;
count = 1;
}
}
public void addNode(Node n){
Node lookingAt = first;
while(lookingAt.next != null){
lookingAt = lookingAt.next;
}
lookingAt.next = n;
count++;
}
public boolean hasLoop(){
int counter = 0;
Node lookingAt = first;
while(lookingAt.next != null){
counter++;
if (count < counter){
return false;
} else {
lookingAt = lookingAt.next;
}
}
return true;
}
private class Node{
Node next;
....
}
}
You could even do it in constant O(1) time (although it would not be very fast or efficient): There is a limited amount of nodes your computer's memory can hold, say N records. If you traverse more than N records, then you have a loop.
Here is my runnable code.
What I have done is to reveres the linked list by using three temporary nodes (space complexity O(1)) that keep track of the links.
The interesting fact about doing it is to help detect the cycle in the linked list because as you go forward, you don't expect to go back to the starting point (root node) and one of the temporary nodes should go to null unless you have a cycle which means it points to the root node.
The time complexity of this algorithm is O(n) and space complexity is O(1).
Here is the class node for the linked list:
public class LinkedNode{
public LinkedNode next;
}
Here is the main code with a simple test case of three nodes that the last node pointing to the second node:
public static boolean checkLoopInLinkedList(LinkedNode root){
if (root == null || root.next == null) return false;
LinkedNode current1 = root, current2 = root.next, current3 = root.next.next;
root.next = null;
current2.next = current1;
while(current3 != null){
if(current3 == root) return true;
current1 = current2;
current2 = current3;
current3 = current3.next;
current2.next = current1;
}
return false;
}
Here is the a simple test case of three nodes that the last node pointing to the second node:
public class questions{
public static void main(String [] args){
LinkedNode n1 = new LinkedNode();
LinkedNode n2 = new LinkedNode();
LinkedNode n3 = new LinkedNode();
n1.next = n2;
n2.next = n3;
n3.next = n2;
System.out.print(checkLoopInLinkedList(n1));
}
}
// To detect whether a circular loop exists in a linked list
public boolean findCircularLoop() {
Node slower, faster;
slower = head;
faster = head.next; // start faster one node ahead
while (true) {
// if the faster pointer encounters a NULL element
if (faster == null || faster.next == null)
return false;
// if faster pointer ever equals slower or faster's next
// pointer is ever equal to slower then it's a circular list
else if (slower == faster || slower == faster.next)
return true;
else {
// advance the pointers
slower = slower.next;
faster = faster.next.next;
}
}
}
boolean hasCycle(Node head) {
boolean dec = false;
Node first = head;
Node sec = head;
while(first != null && sec != null)
{
first = first.next;
sec = sec.next.next;
if(first == sec )
{
dec = true;
break;
}
}
return dec;
}
Use above function to detect a loop in linkedlist in java.
Detecting a loop in a linked list can be done in one of the simplest ways, which results in O(N) complexity using hashmap or O(NlogN) using a sort based approach.
As you traverse the list starting from head, create a sorted list of addresses. When you insert a new address, check if the address is already there in the sorted list, which takes O(logN) complexity.
I cannot see any way of making this take a fixed amount of time or space, both will increase with the size of the list.
I would make use of an IdentityHashMap (given that there is not yet an IdentityHashSet) and store each Node into the map. Before a node is stored you would call containsKey on it. If the Node already exists you have a cycle.
ItentityHashMap uses == instead of .equals so that you are checking where the object is in memory rather than if it has the same contents.
I might be terribly late and new to handle this thread. But still..
Why cant the address of the node and the "next" node pointed be stored in a table
If we could tabulate this way
node present: (present node addr) (next node address)
node 1: addr1: 0x100 addr2: 0x200 ( no present node address till this point had 0x200)
node 2: addr2: 0x200 addr3: 0x300 ( no present node address till this point had 0x300)
node 3: addr3: 0x300 addr4: 0x400 ( no present node address till this point had 0x400)
node 4: addr4: 0x400 addr5: 0x500 ( no present node address till this point had 0x500)
node 5: addr5: 0x500 addr6: 0x600 ( no present node address till this point had 0x600)
node 6: addr6: 0x600 addr4: 0x400 ( ONE present node address till this point had 0x400)
Hence there is a cycle formed.
This approach has space overhead, but a simpler implementation:
Loop can be identified by storing nodes in a Map. And before putting the node; check if node already exists. If node already exists in the map then it means that Linked List has loop.
public boolean loopDetector(Node<E> first) {
Node<E> t = first;
Map<Node<E>, Node<E>> map = new IdentityHashMap<Node<E>, Node<E>>();
while (t != null) {
if (map.containsKey(t)) {
System.out.println(" duplicate Node is --" + t
+ " having value :" + t.data);
return true;
} else {
map.put(t, t);
}
t = t.next;
}
return false;
}
This code is optimized and will produce result faster than with the one chosen as the best answer.This code saves from going into a very long process of chasing the forward and backward node pointer which will occur in the following case if we follow the 'best answer' method.Look through the dry run of the following and you will realize what I am trying to say.Then look at the problem through the given method below and measure the no. of steps taken to find the answer.
1->2->9->3
^--------^
Here is the code:
boolean loop(node *head)
{
node *back=head;
node *front=head;
while(front && front->next)
{
front=front->next->next;
if(back==front)
return true;
else
back=back->next;
}
return false
}
Here is my solution in java
boolean detectLoop(Node head){
Node fastRunner = head;
Node slowRunner = head;
while(fastRunner != null && slowRunner !=null && fastRunner.next != null){
fastRunner = fastRunner.next.next;
slowRunner = slowRunner.next;
if(fastRunner == slowRunner){
return true;
}
}
return false;
}
You may use Floyd's tortoise algorithm as suggested in above answers as well.
This algorithm can check if a singly linked list has a closed cycle.
This can be achieved by iterating a list with two pointers that will move in different speed. In this way, if there is a cycle the two pointers will meet at some point in the future.
Please feel free to check out my blog post on the linked lists data structure, where I also included a code snippet with an implementation of the above-mentioned algorithm in java language.
Regards,
Andreas (#xnorcode)
Here is the solution for detecting the cycle.
public boolean hasCycle(ListNode head) {
ListNode slow =head;
ListNode fast =head;
while(fast!=null && fast.next!=null){
slow = slow.next; // slow pointer only one hop
fast = fast.next.next; // fast pointer two hops
if(slow == fast) return true; // retrun true if fast meet slow pointer
}
return false; // return false if fast pointer stop at end
}
// linked list find loop function
int findLoop(struct Node* head)
{
struct Node* slow = head, *fast = head;
while(slow && fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
return 1;
}
return 0;
}
If the linked list structure implements java.util.List. We can use the list size to keep track of our position in the list.
We can traverse the nodes comparing our current position to the last node's position. If our current position surpasses the last position, we've detected the list has a loop somewhere.
This solution takes a constant amount of space, but comes with a penalty of linearly increasing the amount of time to complete as list size increases.
class LinkedList implements List {
Node first;
int listSize;
#Override
int size() {
return listSize;
}
[..]
boolean hasLoop() {
int lastPosition = size();
int currentPosition = 1;
Node next = first;
while(next != null) {
if (currentPosition > lastPosition) return true;
next = next.next;
currentPosition++;
}
return false;
}
}
Or as a utility:
static boolean hasLoop(int size, Node first) {
int lastPosition = size;
int currentPosition = 1;
Node next = first;
while(next != null) {
if (currentPosition > lastPosition) return true;
next = next.next;
currentPosition++;
}
return false;
}
I'm not sure whether this answer is applicable to Java, however I still think it belongs here:
Whenever we are working with pointers on modern architectures we can expect them to be CPU word aligned. And for a 64 bit architecture it means that first 3 bits in a pointer are always zero. Which lets us use this memory for marking pointers we have already seen by writing 1 to their first bits.
And if we encounter a pointer with 1 already written to its first bit, then we've successfully found a loop, after that we would need to traverse the structure again and mask those bits out. Done!
This approach is called pointer tagging and it is used excessively in low level programming, for example Haskell uses it for some optimizations.
func checkLoop(_ head: LinkedList) -> Bool {
var curr = head
var prev = head
while curr.next != nil, curr.next!.next != nil {
curr = (curr.next?.next)!
prev = prev.next!
if curr === prev {
return true
}
}
return false
}
I read through some answers and people have missed one obvious solution to the above problem.
If given we can change the structure of the class Node then we can add a boolean flag to know if it has been visited or not. This way we only traverse list once.
Class Node{
Data data;
Node next;
boolean isVisited;
}
public boolean hasLoop(Node head){
if(head == null) return false;
Node current = head;
while(current != null){
if(current.isVisited) return true;
current.isVisited = true;
current = current.next;
}
return false;
}
public boolean isCircular() {
if (head == null)
return false;
Node temp1 = head;
Node temp2 = head;
try {
while (temp2.next != null) {
temp2 = temp2.next.next.next;
temp1 = temp1.next;
if (temp1 == temp2 || temp1 == temp2.next)
return true;
}
} catch (NullPointerException ex) {
return false;
}
return false;
}

Categories

Resources