zoukankan      html  css  js  c++  java
  • 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{
                
            }
    
        }
    }
    唯有热爱方能抵御岁月漫长。
  • 相关阅读:
    【BZOJ 2120】 数颜色
    【BZOJ 1878】 HH的项链
    【BZOJ 2038】小Z的袜子
    【BZOJ 2724】 蒲公英
    【POJ 2482】 Stars in Your Windows
    【POJ 2182】Lost Cows
    __align(num) 分析
    C# 获取图片某像素点RGB565值
    基于OpenCV的火焰检测(三)——HSI颜色判据
    基于OpenCV的火焰检测(一)——图像预处理
  • 原文地址:https://www.cnblogs.com/syq816/p/14527900.html
Copyright © 2011-2022 走看看