原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnnhm6/
解法一:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
Stack<ListNode> stack = new Stack();
while(head != null) {
stack.push(head);
head = head.next;
}
if (stack.isEmpty()) {
return null;
}
ListNode node = stack.pop();
ListNode result = node;
while (!stack.isEmpty()) {
ListNode tmpNode = stack.pop();
node.next = tmpNode;
node = node.next;
}
node.next = null;
return result;
}
}
思路:通过栈解决,“先进后出”,先入栈后出栈,链表就反转过来了。
解法二:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode result = null;
while(head != null) {
ListNode tmpNode = head.next;
head.next = result;
result = head;
head = tmpNode;
}
return result;
}
}
思路:使用两个链表,将原来的链表中的节点一个个拆出来,然后拼接到新的链表上即可。
解法三:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode result = reverseList(head.next);
head.next.next = head;
head.next = null;
return result;
}
}
思路:递归,从链表的最后一个节点重新创建一个链表