解题思路
- 栈
- 由栈引申出递归
Java代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode cur = head;
while (cur != null) {
stack.push(cur);
cur = cur.next;
}
if (!stack.empty()) head = stack.pop();
cur = head;
while (!stack.empty()) {
cur.next = stack.pop();
cur = cur.next;
}
if (cur != null) cur.next = null;
return head;
}
}
根据如上算法,根据其原理,实现如下递归:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode tmp = reverseList(head.next);
head.next.next = head;
head.next = null;
return tmp;
}
}