• 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{
                
            }
    
        }
    }
    唯有热爱方能抵御岁月漫长。
  • 相关阅读:
    git add 添加错文件 撤销
    工作流Activiti5.13学习笔记(一)
    instanceof, isinstance,isAssignableFrom的区别
    oracle表查询速度极慢的处理过程记录一下
    类里面的成员变量如果是public,为什么破坏封装
    IPv4 IPv6验证
    枚举使用
    XML之命名空间的作用(xmlns)
    XSD-JAVA
    jaxb
  • 原文地址:https://www.cnblogs.com/syq816/p/14527900.html
Copyright © 2020-2023  润新知