解题思路
- 栈
- 由栈引申出递归
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;
}
}
本文详细介绍了使用栈和递归两种方法实现链表反转的具体步骤,并提供了完整的Java代码示例。通过栈的特性来反转链表是一种直观的方法,而递归则提供了一种更为简洁的解决方案。
1193

被折叠的 条评论
为什么被折叠?



