/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
// 迭代
public ListNode reverseList0(ListNode head) {
ListNode pre = null, next = null;
while (head != null) {
next = head.next;
head.next = pre; //反转
pre = head; //后移
head = next; //后移
}
return pre;
}
// 递归
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head; // return出去的是原始链表的最后一个节点(head.next==null),也会一直冒到最外层return出去。
}
ListNode temp = reverseList(head.next); // 递归
head.next.next = head; //反转。 第一次执行时:head是倒数第二个节点;此处最后一个节点指向倒数第二个节点
head.next = null; //当前节点的next属性置空(防止跑回第一个的时候,n1和n2循环引用了,此操作把n1的next赋值null)。 第一次执行时:倒数第二个节点的next属性指空
return temp; //每次return的都是同一个节点(原始的队尾,新队列的队头)。
}
}