单链表的3中反转方式,附带简单测试。
源码
package suanfa.lianbiao;
import java.util.Stack;
public class ReverseListTest {
public static void main(String[] args) {
Node node1 = new Node(1, null);
Node node2 = new Node(2, node1);
Node node3 = new Node(3, node2);
Node node4 = new Node(4, node3);
Node node5 = new Node(5, node4);
Node node = node5;
out(node);
node = reverseList1(node);
out(node);
node = reverseList2(node);
out(node);
node = reverseList3(node);
out(node);
}
public static Node reverseList1(Node head) {
Node node = null;
while (head != null) {
Node next = head.next;
head.next = node;
node = head;
head = next;
}
return node;
}
public static Node reverseList2(Node head) {
if (head == null || head.next == null) {
return head;
}
Node next = head.next;
head.next = null;
Node node = reverseList2(next);
next.next = head;
return node;
}
public static Node reverseList3(Node head) {
if (head == null) {
return head;
}
Stack<Node> stack = new Stack<>();
while (head != null) {
stack.add(head);
Node next = head.next;
head.next = null;
head = next;
}
Node node = stack.pop();
head = node;
while (!stack.isEmpty()) {
head.next = stack.pop();
head = head.next;
}
return node;
}
private static void out(Node head) {
Node cur = head;
while (cur != null) {
System.out.print(cur.value + " ");
cur = cur.next;
}
System.out.println();
}
public static class Node {
public int value;
public Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
}