双向链表反转

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();

    }
}

 

posted @ 2019-10-07 13:04  踏月而来  阅读(930)  评论(0编辑  收藏  举报