There are 50 ways to leave your lover (P.Simon) but fundamentally 3 ways
to reverse a list
1. Recursively Non-Destructive
2. Recursively Destructive
3. Iteratively
Recursively Non-Destructive:
public ListNode reverse (ListNode list) {
ListNode sofar = new EmptyListNode();
return reverseHelper (this, sofar);
}
private static ListNode reverseHelper (ListNode list1, ListNode sofar) {
if (list1.isEmpty()) {
return sofar;
} else {
return reverseHelper (list1.rest() , new NonemptyListNode (list1.first(), sofar) );
}
}
Recursively Destructive:
public void reverse2 () {
myHead = reverse2Helper (myHead, null);
}
public static ListNode reverse2Helper (ListNode L, ListNode soFar){
if (L == null){
return soFar;
} else {
ListNode temp = L.myRest;
L.myRest = soFar;
return reverse2Helper (temp, L) ;
}
}
Iteratively:
public void reverse3 () {
myHead = reverse3Helper (myHead);
}
public static ListNode reverse3Helper (ListNode head){
ListNode p, soFar;
for (p = head, soFar = null; p != null;){
ListNode temp = p.myRest;
p.myRest = soFar;
soFar = p;
p = temp;
}
return soFar;
}
Sunday, November 18, 2007
3 ways to REVERSE a list (singly linked)
Subscribe to:
Post Comments (Atom)
Just some daily notes ...
Things I'm into now...
Blog Archive
-
▼
2007
(29)
-
▼
November
(14)
- Declaring an Edge Adjacency List Graph
- MaximallyBalanced or Complete Binary Tree
- Calculating the Height of a Tree
- Adding to a Circular Doubly Linked List
- 3 ways to REVERSE a list (singly linked)
- Reversing a List Iteratively!
- Doubling a Linked List
- Access Modifiers: public, private, proctecd, packa...
- End of HFJ
- Format Specifiers
- Collection class tidbits...
- Generic class definitions and one implementation
- doubling a List
- Don't Forget Your Scheme!
-
▼
November
(14)

No comments:
Post a Comment