面试之路(21)-链表的倒序实现

链表的倒序实现

思路分析:

  • 改变链表的形状是不妥的,需要和面试官沟通
  • 采用stack来存储遍历的节点,因为递归可以来实现stack的功能,也可以采用递归实现

java代码:

stack实现:

class ListNode{
        int key;
        ListNode next;
    }
    void reverseStack(ListNode head){
        Stack st = new Stack();
        while(head != null){
            st.push(head);
            head =head.next;
        }
        while(!st.isEmpty()){
            head = (ListNode) st.pop();
            System.out.println(head.key+"");
        }
    }

递归实现

class ListNode{
        int key;
        ListNode next;
    }
    void reverse(ListNode head){
    if(head != null){
        if(head.next != null){
            reverse(head.next);
        }
                  System.out.println(head.key+"");
    }   
}

你可能感兴趣的:(java,递归,链表,面试,存储)