• 双向链表反转


    public class MyBiLinkedList {
    
        Node head;
    
        Node tail;
    
        public Node getLast() {
            // temp变量来保存链表的最后那个节点
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            // 循环结束时,temp就是最后那个节点
            return temp;
        }
    
        // 添加新节点到链表尾部
        public void append(int obj) {
            Node node = new Node(obj);
            if (head == null) {
                head = node;
            } else {
                Node last = getLast();
                // 添加新节点
                last.next = node;
                node.prev = last;
                tail = node;
            }
        }
    
        public void display() {
            Node temp = head;
            StringBuilder sb = new StringBuilder();
            while (temp != null) {
                sb.append(temp.value + " -> ");
                temp = temp.next;
            }
            String res = sb.substring(0, sb.lastIndexOf(" -> "));
            System.out.println(res);
        }
    
        public void display2() {
            Node temp = tail;
            StringBuilder sb = new StringBuilder();
            while (temp != null) {
                sb.append(temp.value + " -> ");
                temp = temp.prev;
            }
            String res = sb.substring(0, sb.lastIndexOf(" -> "));
            System.out.println(res);
        }
    
        public static class Node {
            Node prev;
            Node next;
            int value;
    
            public Node(int value) {
                super();
                this.value = value;
            }
    
            public Node() {
    
            }
        }
    
        // 反转双向链表
        public void reverse() {
            Node pre = null;
            Node next = null;
            while (head != null) {
                next = head.next;
                head.next = pre;// ->改为<-
                head.prev = next;// <-改为->
                pre = head;// pre右移
                head = next;// head右移
            }
            head = pre;
        }
    
        public static void main(String[] args) {
    
            MyBiLinkedList linkedList = new MyBiLinkedList();
            linkedList.append(5);
            linkedList.append(4);
            linkedList.append(3);
            linkedList.append(2);
            linkedList.append(1);
            linkedList.display();
            linkedList.reverse();
            linkedList.display();
    
        }
    }
  • 相关阅读:
    输入法searchLookUpEditd的使用
    DevExpress GridControl使用方法总结
    DevExpress 控件中GridControl的使用
    MSSQl 事务的使用
    Python class NameError name "xxx" is not defined
    win 10 slmgr.vbs -xpr 无法运行,被豆麦笔记打开解决方法
    git checkout 撤销多个文件,撤销整个文件夹
    Python argparse 模块,参数传递
    Python Enum 枚举 用法汇总
    git branch & checkout fetch 的使用和冲突解决
  • 原文地址:https://www.cnblogs.com/moris5013/p/11630078.html
Copyright © 2020-2023  润新知