Skip to content

Instantly share code, notes, and snippets.

@saurzcode
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saurzcode/bed52655f7e7f5a72064 to your computer and use it in GitHub Desktop.
Save saurzcode/bed52655f7e7f5a72064 to your computer and use it in GitHub Desktop.
Reverse a list using Iteration
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