题目
事先给定的代码
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x)
{
val = x;
}
}
思路
解法一
这种反转链表的题目首先想到的就是使用栈。构建一个辅助栈,对链表进行一次正序遍历,并将节点存入栈中,然后再一个一个出栈即可。
public int[] ReversePrint(ListNode head)
{
ListNode cur = head;
Stack<int> stack = new();
while (cur != null)
{
stack.Push(cur.val);
cur = cur.next;
}
int[] res = new int[stack.Count];
for (int j = 0; j < res.Length; j++)
{
res[j] = stack.Pop();
}
return res;
}
解法二
另一种解法就是使用递归。不过本质上与解法一一样,只不过从手动创建的栈换成了系统内部的栈。采用递归的方法就需要额外的数据结构存储递归产生的结果。这里使用了一个定长数组,可以避免数组扩充导致额外的时间消耗,但也额外消耗了空间。也可以使用List之类的可变数组,各有优劣。
private int[] _arr = new int[10000];
private int _index = 0;
public int[] ReversePrint2(ListNode head)
{
Reverse(head);
int[] res = new int[_index];
for (int i = 0; i < _index; i++)
{
res[i] = _arr[i];
}
return res;
}
private void Reverse(ListNode node)
{
if(node == null)
return;
Reverse(node.next);
_arr[_index++] = node.val;
}