题目:反转链表
方法一:双链表
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode newHead = null;
ListNode next;
while (head != null) {
next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
}
方法二:递归
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = ReverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
方法三:尾递归
public class Solution {
public ListNode ReverseList(ListNode head) {
return reverseList(head, null);
}
private ListNode reverseList(ListNode head, ListNode prev) {
if (head == null) {
return prev;
}
ListNode next = head.next;
head.next = prev;
return reverseList(next, head);
}
}
方法四:栈
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ArrayDeque<ListNode> stack = new ArrayDeque<>();
while (head.next != null) {
stack.push(head);
head = head.next;
}
ListNode newHead = head;
while (!stack.isEmpty()) {
head.next = stack.pop();
head = head.next;
}
// 原头结点的 next 设置为 null
head.next = null;
return newHead;
}
}