迭代解法:
1、首先将head指向null
2、然后对next往下遍历的同时让他指向前一个
3、为了保证往下指向,使用temp暂存next.next
public ListNode reverseList(ListNode head) { if (head == null || head.next == null){ return head; } ListNode next = head.next; head.next = null; while(next != null){ ListNode temp = next.next; next.next = head; head = next; next = temp; } return head; }递归解法:
将问题转换为让每一个节点的指针指向他前面的节点
递归就是先遍历到最后一个节点,然后让他指向前一个节点,结束
因为有系统栈所以他的前一个节点被保存下来,继续递归的进行
也就是假设列表的其余部分已经被反转
public ListNode reverseList(ListNode head) { if (head == null || head.next == null){ return head; } ListNode reverse = reverse(head, head.next); head.next = null; return reverse; } private ListNode reverse(ListNode node, ListNode next){ if (next == null){ return node; } ListNode head = reverse(node.next, next.next); next.next = node; return head; }