首页 > 其他 > 详细

双向链表反转

时间:2019-10-07 13:42:01      阅读:95      评论:0      收藏:0      [点我收藏+]
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();

    }
}

 

双向链表反转

原文:https://www.cnblogs.com/moris5013/p/11630078.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!