Results 1 to 5 of 5
Thread: Doubly linked list, reverse()
- 10-29-2010, 03:01 AM #1
Member
- Join Date
- Sep 2010
- Posts
- 11
- Rep Power
- 0
Doubly linked list, reverse()
Hi. I have a Doubly-linked list and i need to reverse it. I'm not sure if the method that i wrote works. It's a lil bit tricky. Would you plz correct this method if there is any thing wrong with this code?
Appreciate it
public void reverse()
{
if (first == null)
return;
DoubleNode previous = first;
DoubleNode current = first.next;
first.next = null;
while (current != null)
{
DoubleNode next = current.next;
current.next = previous;
previous = current;
current = next;
}
first = previous;
}
- 10-29-2010, 03:56 AM #2
Looks like it would work to me, just write some code and test away. If there are any errors, post back.
Sincerely, Joshua Green
Please REP if I help :)
- 10-29-2010, 03:58 AM #3
Member
- Join Date
- Sep 2010
- Posts
- 11
- Rep Power
- 0
Thanks guys.
- 10-29-2010, 09:25 AM #4
Senior Member
- Join Date
- Feb 2010
- Location
- Ljubljana, Slovenia
- Posts
- 470
- Rep Power
- 4
Why don't you take advantage of the fact you have a doubly linked list? All you would need is an additional variable to tell you what direction you're going, then all you'd need to do is change the variable that points to the first element and change direction:
Also note that this example will produce errors if used like this, you'd have to check if the current element is null etc etc.Java Code:public class DoublyLinkedList { Node first, current; boolean forward; //constructors... methods... private Node next() { if(forward) return current.next(); else return current.previous(); } public void reverse() { while(true) { if(next() == null) { first = current; forward = !forward; return; } current = next(); } } }Ever seen a dog chase its tail? Now that's an infinite loop.
- 10-29-2010, 09:53 AM #5
Member
- Join Date
- Sep 2010
- Posts
- 11
- Rep Power
- 0
Similar Threads
-
Sorted Doubly linked List
By student2889 in forum New To JavaReplies: 1Last Post: 10-14-2010, 10:05 AM -
Doubly Linked List
By matin1234 in forum New To JavaReplies: 0Last Post: 06-02-2010, 05:58 AM -
doubly linked list insert
By ineedhelpwithjava in forum Advanced JavaReplies: 1Last Post: 03-20-2009, 02:05 PM -
Help with Doubly linked list
By Dr Gonzo in forum New To JavaReplies: 5Last Post: 12-06-2008, 07:45 AM -
Doubly-linked list with data structure
By Java Tip in forum java.langReplies: 0Last Post: 04-16-2008, 10:30 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks