加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

双向链表反转

发布时间:2020-12-14 04:39:54 所属栏目:大数据 来源:网络整理
导读: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 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();

    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读