包括三个版本,递归、栈、以及算法版
package com.test;
import java.util.Stack;
public class ReverseList {
public static void reverse(Node head) {
if (head.next == null || head == null) {// 局部变量表内容越多,栈帧越大,栈深度越小。
return;
}
reverse(head.next);
head.next.next = head;
head.next = null;
}
public static void reverseNonRecursive(Node head) {
if (head.next == null || head == null) {//如果都不够两个就终止
return;
}
Stack<Node> stack = new Stack<>();
while (head != null) {
stack.push(head);
head = head.next;
}
Node temp_1 = stack.pop();//存储出来的那个
while (!stack.empty()) {
Node temp_2 = stack.pop();
temp_1.next = temp_2;
temp_2.next = null;
temp_1 = temp_2;
}
}
public static void reverse2(Node head) {//直接遍历
if (head.next == null || head == null) {//如果都不够两个就终止
return;
}
Node pre = head;
Node cur = head.next;
while (cur.next != null) {//调整的是pre 和 cur之间的 方向, 跳出之后最后一次别忘调整
Node temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
head.next =null;//最初的head也没调整
cur.next = pre;
}
public static void main(String[] args) {
Node a = new Node(1);
Node b = new Node(2);
Node c = new Node(3);
a.next = b;
b.next = c;
reverseNonRecursive(a);
System.out.println("finished");
}
}
class Node {
int value;
Node next = null;
Node(int value) {
this.value = value;
}
}
另附剑指offer版本
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null){
return null;
}
if(head.next == null){
return head;
}
ListNode pre = null;
ListNode next = null;//关键点,需要保存next
while (head != null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}