通过栈结构使单向链表反向

用List来模拟 栈结构,并提供push()和pop()方法实现栈的先进后出特性:

public class Stack {
    private List<ListNode> list;

    public Stack() {
        list = new ArrayList<>();
    }

    public ListNode getLastNode(){
        return list.get(list.size()-1);
    }

    public int getSize(){
        return list.size();
    }

    public ListNode pop(){
        ListNode o = list.get(list.size()-1);  //后进先出
        list.remove(o);
        return o;
    }
    public void push(ListNode o){
        list.add(o);
    }

}

定义链表类:

public class MyList {
    private ListNode head;

    public MyList(ListNode head) {
        this.head = head;
    }

    public ListNode getHead() {
        return head;
    }

    public void setHead(ListNode head) {
        this.head = head;
    }
}

链表节点:

public class ListNode {
    private int data;
    private ListNode next;

    public ListNode() {
    }
    
    public ListNode(int data, ListNode next) {
        this.data = data;
        this.next = next;
    }
    
    public ListNode(int data) {
        this.data = data;
    }
    public ListNode getNext() {
        return next;
    }
    public int getData() {
        return data;
    }
    public void setData(int data) {
        this.data = data;
    }
    public void setNext(ListNode next) {
        this.next = next;
    }
}

最后便是 测试类:

public class ListTest {
    public static void main(String[] args) {
        ListNode head = new ListNode(3);
        MyList myList = new MyList(head);
        ListNode node1 = new ListNode(5);
        head.setNext(node1);
        ListNode node2 = new ListNode(51);
        node1.setNext(node2);
        ListNode node3 = new ListNode(15);
        node2.setNext(node3);
        ListNode node4 = new ListNode(52);
        node3.setNext(node4);
        ListNode node5 = new ListNode(25);
        node4.setNext(node5);

        nodePrint(myList);

        putList(myList);

        System.out.println();
        nodePrint(myList);

    }
    // 输出链表的各节点
    public static void nodePrint(MyList mylist){
        ListNode node = mylist.getHead();
        while(node != null){
            System.out.print(node.getData()+" ");
            node=node.getNext();
        }
    }
    /**
     *链表入栈,将最后一个节点变为头节点
     *链表出栈,将指针反向
     * @param myList 链表
     * */
    public static void putList(MyList myList){
        Stack stack = new Stack();
        ListNode node = myList.getHead();
        while (node != null){
            stack.push(node);  //入栈
            if(node.getNext()==null){  //如果下一个节点为null,表示到了链表的末尾
                myList.setHead(node);  //把此时这个节点作为头节点
            }
            node=node.getNext();
        }
        while(true){
            node = stack.pop();
            if(stack.getSize()==0){
                node.setNext(null);
                break;
            }
            node.setNext(stack.getLastNode());
        }
    }
}

 

 

 

©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页