OregonDuck OregonDuck - 2 months ago 15
Java Question

Java do while loop keeps loop even it not meets the condition

My

while(cur!=head)
is supposed to execute at node4, since it starts
at node3, the program executes the statement in
do
block at least once , then it will read at node4, node4 is same to head node which is node3.

My program is supposed to return.

Actual output: 3 3 3 3 4 5 1 2

Expected output: 3 3 3 4 5 1 2 3


The actual output is correct, my expected output is wrong.However, I
am just wondering, when cur is equal to head, which not qualify to the
condition
while(cur!=head)
, but it can keep running? Why?

class LinkedNode
{
int val;
LinkedNode next;
LinkedNode (int x)
{
val = x;
next = null;
}
}



class Solution
{

public static void main(String[] args)
{
LinkedNode node1 = new LinkedNode(1);
LinkedNode node2 = new LinkedNode(2);
LinkedNode node3 = new LinkedNode(3);
LinkedNode node4 = new LinkedNode(3);
LinkedNode node5 = new LinkedNode(3);
LinkedNode node6 = new LinkedNode(3);
LinkedNode node7 = new LinkedNode(4);
LinkedNode node8 = new LinkedNode(5);

node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
node6.next = node7;
node7.next = node8;
node8.next = node1;

LinkedNode after = check(node3);
print_list(after);
}


public static void print_list(LinkedNode head)
{
LinkedNode cur = head;
do
{
System.out.print(head.val + " ");
head = head.next;
}
while (cur!= head);//same question as the below
}

public static LinkedNode check(LinkedNode head)
{

LinkedNode cur = head;
do
{
cur = cur.next;
}
while(cur!=head);// this line is supposed to execute and exit at node4,since node4 is equal to node3(head)

return cur;
}

}

Answer

You are comparing the objects by reference not value. Your logic is correct. Node 3 is never equal to Node 4, since they are separate objects, but what you want is to compare their value.

while(cur.val != head.val)
Comments