您的位置:首页 > 职场人生

【刷题】面试题06. 从尾到头打印链表

2020-04-02 18:37 549 查看

难度简单12输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

分析:可以通过栈的方式辅助,也可以通过递归的方式实现,官方提过的两次遍历方法。

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
//遍历两次法
public int[] reversePrint(ListNode head) {
ListNode list=head;
int size=0;
while(null!=list){
size++;
list=list.next;
}
int[] nums=new int[size];
for(int i=nums.length-1;i>=0;i--){
nums[i]=head.val;
head=head.next;
}
return nums;
}

//堆栈方法
// public int[] reversePrint(ListNode head) {
//      Stack<Integer> stack=new Stack<Integer>();
//      while (null != head){
//          stack.push(head.val);
//          head=head.next;
//      }
//      int[] nums=new int[stack.size()];
//      for (int i=0;i<nums.length;i++){
//          nums[i]=stack.pop();
//      }
//      return nums;
//  }
//递归方法
// ArrayList<Integer> tmp = new ArrayList<Integer>();
// public int[] reversePrint(ListNode head) {
//     recur(head);
//     int[] res = new int[tmp.size()];
//     for(int i = 0; i < res.length; i++)
//         res[i] = tmp.get(i);
//     return res;
// }
// void recur(ListNode head) {
//     if(head == null) return;
//     recur(head.next);
//     tmp.add(head.val);
// }
}
  • 点赞
  • 收藏
  • 分享
  • 文章举报
xiaolu_333 发布了30 篇原创文章 · 获赞 0 · 访问量 471 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: