import org.junit.Test;
import java.util.List;
public class ReverseListNode {
public static void main(String[] args) {
ListNode[] reverselist = new ListNode[5];
for (int i = 0; i < 5; i++) {
reverselist[i] = new ListNode();
reverselist[i].val = i;
}//必须初始化完了再进行链表的链接,不然链接为空
for (int i = 0; i < 5; i++) {
if (i == 0) {
reverselist[i].head = null;
} else {
reverselist[i].head = reverselist[i - 1];
}
if (i == 4) {
reverselist[i].next = null;
} else {
reverselist[i].next = reverselist[i + 1];
}
}
ListNode reverse = reverseList(reverselist[0]);
System.out.println(reverse);
while (reverse != null) {
System.out.println(reverse.val);
reverse = reverse.next;
}
}
public static ListNode reverseList(ListNode head) {
/* //双指针
ListNode left;
ListNode right;
ListNode temp;
left = head;
right = null;
while (left != null) {
temp = left.next;
left.next = right;
right = left;
left = temp;
}
return right;
*/
ListNode temp = recursionListNode(head, null);
return temp;
}
/*递归求链表尾,然后返回的每一层翻转指针指向。
//最后一层current为空,返回previous即尾结点,上一层的current即返回的previous
0 1 2 3 4 null
previous current
//递归后层层将current.next指向previous即可。
0 1 2 3 4 null
previous current
0 1 2 3 4 null
previous current
*/
private static ListNode recursionListNode(ListNode current, ListNode previous) {
if (current == null) {
return previous;
}
ListNode recursiontemp = recursionListNode(current.next, current);
current.next = previous;
return recursiontemp;
}
}
class ListNode {
int val;
ListNode head;
ListNode next;
}