Linked Lists - hard exercise(help needed)
hello
i came across a really difficult exercise about linked lists..
and i cant seem to solve it
here's the question
there's a doubly linked list which is also circled (i.e the last node's next pointer points to the head of the list,and the head's prev pointer points to the last node).
the data in each node is an integer.
now a jump in a circular list is as follows:
if we have a node p :
if p.data is positive we move p.data times using the next pointer
if p.data is negative we move p.data times using the prev pointer
if p.data is 0 we dont move at all.
now you need to write a method that recieves as a paramater a pointer to the head of the list , and returns true if threre's a path that starts from the head node and ends there.
an example:
2-->14-->-5--> 1-->-4-->1
for this list the method will return true,because we start with 2 ,move to -5,
then move to 1(moving backwords) ,then -4 ,and then 2.
this is not homework(i'm working on different exercises in order to prepare my self to an exam)
help will be appreciated..
thank you very much.
[1216 byte] By [
parallel] at [2007-11-11 7:55:32]

# 2 Re: Linked Lists - hard exercise(help needed)
i only had one idea concerning the distance between the nodes,but i couldn't develop it,so i'm actually in a dead end.
i just can't seem to grasp the principle of this question
and of course my main problem is :when should i return false.
just forgot to mention: you are not allowed to create new objects
# 3 Re: Linked Lists - hard exercise(help needed)
Well, think about it logically. We return true if after going through the sequence we return at the head. Well, if we come back to any other number besides the head, it will never read the head.
eg: 1, 1, 2. This will go from position 0 to 1, then 1 to 2, then 2 to 1. We know that this will never reach the head again.
Hope this helps!
destin at 2007-11-11 22:39:00 >

# 4 Re: Linked Lists - hard exercise(help needed)
Okay here's something that does what you want. I purposely used another object because I know you're not allowed.
ArrayList<Integer> index = new ArrayList<Integer>();
int position = 0;
while (!index.contains(position)) {
index.add(position);
position = (linkedList.get(position) + position) % linkedList.size();
if (position < 0) {
position += linkedList.size();
}
}
if (position == 0) {
System.out.println("good!");
} else {
System.out.println("bad!");
}
destin at 2007-11-11 22:40:06 >
