题目来源
题目描述
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
vector<int> reverseBookList(ListNode* head) {
}
};
题目解析
使用stack
栈的特点是后进先出,即最后压入栈的元素最先弹出。考虑到栈的这一特点,使用栈将链表元素顺序倒置。从链表的头节点开始,依次将每个节点压入栈内,然后依次弹出栈内的元素并存储到数组中。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
Stack<Integer> stack = new Stack<>();
while (head != null) {
stack.push(head.val);
head = head.next;
}
int size = stack.size();
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = stack.pop();
}
return array;
}
}
链表反转
反转链表的同时记下链表长度,然后填充数组
class Solution {
public int[] reversePrint(ListNode head) {
ListNode pre = null;
ListNode cur = head;
int size = 0;
while (cur != null){
ListNode t = cur.next;
cur.next = pre;
pre = cur;
cur = t;
size++;
}
int[] arr = new int[size];
size = 0;
while (pre != null){
arr[size++] = pre.val;
pre = pre.next;
}
return arr;
}
}
反向填充数组
先求出链表长度,构建数组,然后反向填充数组
class Solution {
public int[] reversePrint(ListNode head) {
int size = 0;
ListNode temp = head;
while (head != null){
head = head.next;
size++;
}
int[] arr = new int[size];
for (int i = size - 1; i > -1 ; i--){
arr[i] = temp.val;
temp = temp.next;
}
return arr;
}
}
vector<int> reversePrint(ListNode* head) {
vector<int> ans;
ListNode *iter = head;
while (iter){
ans.insert(ans.begin(), iter->val);
iter = iter->next;
}
return ans;
}
递归
一个后序遍历
class Solution {
vector<int> ans;
void helper(ListNode* head){
if(head == nullptr){
return;
}
helper(head->next);
ans.emplace_back(head->val);
}
public:
vector<int> reversePrint(ListNode* head) {
helper(head);
return ans;
}
};