反转链表的方法如下:
反转方法
public void reverseList() {
Node<E> curr = head;
Node<E> pre = null;
Node<E> incoming = null;
while(curr != null) {
incoming = curr.next;
curr.next = pre;
pre = curr;
curr = incoming;
}
head = pre;
}
反转列表需要三个引用: pre、curr和incoming
... pre curr incoming
... --> (n-1) --> (n) --> (n+1) --> ...
为了反转一个节点,你需要存储前一个元素,以便可以使用简单的语句;
curr.next = pre
要反转当前元素的方向。但是,为了遍历整个列表,在执行上述语句之前必须存储传入的元素,因为在反转当前元素的下一个引用时,您不再知道传入的元素,这就是为什么需要第三个引用。
演示代码如下:
LinkedList示例类
public class LinkedList<E> {
protected Node<E> head;
public LinkedList() {
head = null;
}
public LinkedList(E[] list) {
this();
addAll(list);
}
public void addAll(E[] list) {
for(int i = 0; i < list.length; i++)
add(list[i]);
}
public void add(E e) {
if(head == null)
head = new Node<E>(e);
else {
Node<E> temp = head;
while(temp.next != null)
temp = temp.next;
temp.next = new Node<E>(e);
}
}
public void reverseList() {
Node<E> curr = head;
Node<E> pre = null;
Node<E> incoming = null;
while(curr != null) {
incoming = curr.next;
curr.next = pre;
pre = curr;
curr = incoming;
}
head = pre;
}
public void printList() {
Node<E> temp = head;
System.out.print("List: ");
while(temp != null) {
System.out.print(temp + " ");
temp = temp.next;
}
System.out.println();
}
public static class Node<E> {
protected E e;
protected Node<E> next;
public Node(E e) {
this.e = e;
this.next = null;
}
@Override
public String toString() {
return e.toString();
}
}
}
测试代码
public class ReverseLinkedList {
public static void main(String[] args) {
Integer[] list = { 4, 3, 2, 1 };
LinkedList<Integer> linkedList = new LinkedList<Integer>(list);
linkedList.printList();
linkedList.reverseList();
linkedList.printList();
}
}
输出
List: 4 3 2 1
List: 1 2 3 4