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

来源:互联网 发布:乡村学生教育数据 编辑:程序博客网 时间:2024/06/06 03:23

链表的倒序实现

思路分析:

  • 改变链表的形状是不妥的,需要和面试官沟通
  • 采用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+"");    }   }
0 0