easiest way to reverse a linked list is to create new head pointer, iterate through the list take the item from the list and add it to the front of the list.
here's the full code in java.
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
private Node head;
public LinkedList() {
this.head = null;
}
public void reverse() {
Node cur = head;
head = null;
while(cur != null) {
Node temp = cur;
cur = cur.next;
temp.next = head;
head = temp;
}
}
}
if you're interested in more methods of linked lists, you may want to read these posts as well:
- · linked lists revisited — implementations are from the book introduction to algorithms.
- · linked lists and bitwise operators — a simple hacking of linked lists.