Last active
August 29, 2015 14:02
-
-
Save saurzcode/bed52655f7e7f5a72064 to your computer and use it in GitHub Desktop.
Reverse a list using Iteration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public Node<E> reverseList(Node<E> headList) { | |
Node<E> current = headList; | |
Node<E> next = null; | |
Node<E> result = null; | |
while (current != null) { | |
next = current.next; | |
current.next = result; | |
result = current; | |
current = next; | |
} | |
head = result; | |
return head; | |
} | |
public void reverseListRecursive(Node<E> headList) { | |
if (headList == null) | |
return; | |
Node<E> firstNode = headList; | |
Node<E> restNode; | |
restNode = firstNode.next; | |
if (restNode == null){head = headList; | |
return; | |
} | |
reverseListRecursive(restNode); | |
firstNode.next.next = firstNode; | |
firstNode.next = null; | |
headList = restNode; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment