Java实现链表反转(借助栈实现)

public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }

    // 添加新的结点
    public void add(int newval) {
        ListNode newNode = new ListNode(newval);
        if (this.next == null)
            this.next = newNode;
        else
            this.next.add(newval);
    }

    // 打印链表
    public void print() {
        System.out.print(this.val);
        if (this.next != null) {
            System.out.print("-->");
            this.next.print();
        }

    }
}
import java.util.Stack;

public class ListReverse {
    public ListNode ReverseList(ListNode head) {
        Stack<ListNode> stack = new Stack<ListNode>();
        ListNode node = head;
        if (head == null) {
            return null;
        }
        while (node != null) {
            stack.push(node);
            node = node.next;
        }
        ListNode newHead = new ListNode(stack.pop().val);
        ListNode tmp = newHead;
        while (stack.size() > 0) {
            node = stack.pop();
            ListNode newtmp = new ListNode(node.val);
            tmp.next = newtmp;
            tmp = newtmp;
        }
        return newHead; // 在最后添加上null作为结束标志
    }

    public static void main(String[] args) {
        ListNode l1 = null; // 创建链表对象 l1 (对应有参 和 无参 构造方法)
        if (l1 != null) {
            l1.print();
            ListReverse lr = new ListReverse();
            ListNode reverseList = lr.ReverseList(l1);
            System.out.println();
            reverseList.print();
        }else{
            
        }

    }
}
唯有热爱方能抵御岁月漫长。
原文地址:https://www.cnblogs.com/syq816/p/14527900.html