Click to See Complete Forum and Search --> : doubly linked list


kayl
October 25th, 2004, 01:40 PM
In reversing a doubly linked list ... i think the idea is to
1- swap head and tail
2- swap the next and previous for each node .

but the problem is how can u reach each individual node to swap its references.

// swap tail and head
Node temp = tail;
tail = head;
head = temp;

Node first = temp.getNext();

while( first != null ) {
// swap next and previous for first

first = first.getNext() // the problem is here on this line .. that is that first now

is the ( tail ) so i cant go to the next node to swap its references ....

Please anyone can help ....

Ejaz
October 29th, 2004, 01:08 AM
The apparent problem is, when you swap the pointers, like for the first node, the previous will be NULL and next will be some other node address, when it will be swaped, the previous will contain the address and next will contain the NULL and your loop will be terminated.

What you can do is, take another pointer, which also point at the head in the start (say current) and then use current to traverse the linklist, while the first will be following the current. something like


Node current = temp.getNext();
Node first = temp.getNext();

while( current != null )
{
current = current.getNext(); // Now current is ahead of first

// Swap your pointers of the first variable here

first = current; // Now first and current are on the same node
}


The above code is for your reference and it may contain typo errors.