Reversing Singly Linked List?
On d开发者_高级运维ifferent sites, i was looking for programme in java doing reversing the order of linked list(Singly Linked List and and doubly linked list) .I landed up on different sites like
1)http://geek-o-pedia.blogspot.com/2007/07/how-would-you-reverse-singly-linked.html 2)http://stackoverflow.com/questions/354875/reversing-a-linked-list-in-java-recursively
PointA-As per my understanding these programmes(take link 1) are good when you are writing your linked list class as the programme is assuming we can access Node class which we can not(As its is private inner class in Linked List.)
Point B-Apart from that this programme will permanently reverse the order of Source linked list. So when we iterate on this we will always get the elemts in reverse order.
Please let me know if both the above points are correct
So i tried to do it myself
--Reversing the singly Linked List
LinkedList list1 = new LinkedList();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
list1.add(5);
LinkedList reverseList1 = new LinkedList();
int size= list1.size();
// below loop will revrse the order of source linked list i.e list1
for(int i =size-1;i>=0;i--)
{
reverseList1.add(size-i-1, list1.get(i));
}
Just wanted to ensure if above approach is correct as i could not find these approach on internet which i found very simple .Everywhere i could find the approach similar to link1 and link2
posted at https://forums.oracle.com/forums/thread.jspa?threadID=2271413&tstart=0 too but did not get proper answer.
This seems like it would work fine. However, there is no need for the 1st parameter for the add
method - add already inserts at the end (and you can also use addLast
, which is identical).
Also, using get(i)
that many times isn't efficient. I would iterate over the first list (with foreach or with an iterator - , and for each element call addFirst
.
Alternatively, use Collections.reverse
, as panzerschreck suggested, which really is the best way IMO.
Did you try using any of these ?
Collections.sort(list, Collections.reverseOrder(cmp));
or
Collections.reverse(list);
精彩评论