• 双向链表反转


    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();
    
        }
    }
  • 相关阅读:
    ios添加第三方字体
    IOS 适应各种iphone屏幕尺寸
    sqlite第三方类库FMDB的使用
    IOS--沙盒机制
    用plist建立UITabController
    Xcode7 使用NSURLSession发送HTTP请求报错[转]
    网络开发--NSURLConnection类的简单介绍
    TF-IDF
    《汇编语言》——王爽 第12章 内中断
    操作系统 L4操作系统接口+L5系统调用的实现(网易公开课)
  • 原文地址:https://www.cnblogs.com/moris5013/p/11630078.html
Copyright © 2020-2023  润新知