public class LinkedListReversal {
static class ListNode{
int val;
ListNode next;
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static void main(String[] args) {
ListNode node5 = new ListNode(5, null);
ListNode node4 = new ListNode(4, node5);
ListNode node3 = new ListNode(3, node4);
ListNode node2 = new ListNode(2, node3);
ListNode node1 = new ListNode(1, node2);
ListNode recursion = recursion(node1);
System.out.println(recursion);
}
public static ListNode iterate(ListNode head){
ListNode prev = null,next;//循环的下一个节点标记
ListNode curr = head;
while (curr!=null){
next = curr.next; // 把当前节点(如1)的下一个节点(如2)标记起来做循环条件
curr.next = prev; // 把当前节点(如1)的前一个节点(如1的前一个节点是null)变成反转后的下一个节点
prev = curr; // 把当前节点(如1)标记成下一个节点(如2)的上一个节点
curr = next; // 把标记的要循环的下一个节点赋值给curr,循环就从2开始
}
return prev;
}
public static ListNode recursion(ListNode head){
if (head ==null || head.next ==null){
return head;
}
ListNode recursion = recursion(head.next);
head.next.next = head;
head.next = null;
return recursion;
}
}