Click to See Complete Forum and Search --> : java linked list help? reversing without access to head?


Fryguy8
03-01-2004, 10:10 PM
Just had a test a week ago, and one of the questions was to reverse a linked list using this following method header:

static void reverse1(Node list) {}

We have developed a linked list from scratch in our class (data structures), and there is no accessor method for the head of the list. now I have code to reverse a linked list designed to be put into the Linked List class:

public void reverse()
{
IntegerNode cur = head;
IntegerNode next = head.next;
IntegerNode prev = null;
while (next!=null)
{
cur.next=prev;
prev=cur;
cur=next;
next=next.next;
}
cur.next=prev;
head=cur;
}

However, modifying the code so that IntegerNode cur = head; is removed and you use the method parameter instead doesn't work since you don't have direct access to the head, you can't pass it into a function. Not really sure what to do here.

Teacher said the entire 2 classes got it wrong and is giving it to us for makeup.

Any ideas? (btw, it has to be an efficient algorithm like above, can't use a stack or anything)

binaryDigit
03-02-2004, 03:06 PM
you don't need direct access to the head of the list if you have a prev pointer.

while( item.prev != NULL ) item = item.prev;

at the end *item* will be at the head.

Fryguy8
03-02-2004, 07:46 PM
Singly linked list, no .prev pointer.

binaryDigit
03-02-2004, 08:29 PM
:o my mistake. i should pay more attention.

in a singly linked list you should always track the head of the list. unless you make the next pointer of the last item point back to the head. otherwise there is no way to get back to the head of the list.