反转链表 单向和双向链表 附代码

反转一个单链表

public class Main {
    public static void main(String[] args) {
        Node head1 = new Node(0);
        Node node = head1;
        for (int i = 1; i < 6; i++) {
            node.next = new Node(i);
            node = node.next;
        }
        node = reverseList(head1.next);
        while (node != null){
            System.out.print(node.value + " ");
            node = node.next;
        }
        return;
    }
    public static Node reverseList(Node head){
        Node pre = null;
        Node cur = head;
        Node post;
        while (cur != null){
            post = cur.next;
            cur.next = pre;
            pre = cur;
            cur  = post;
        }
        return pre;
    }
}

反转一个双向链表

public class Main {
    public static void main(String[] args) {
        DoubleNode head = new DoubleNode(0);
        DoubleNode node = head;
        DoubleNode pre = null;
        for (int i = 1; i < 6; i++) {
            node.last = pre;
            node.next = new DoubleNode(i);
            pre = node;
            node = node.next;
        }
        node.last = pre;
        DoubleNode node1 = head;
        DoubleNode node2 = node;
        node1 = reverseList(head);
        while (node1 != null){
            System.out.print(node1.value);
            node1 = node1.next;
        }
        System.out.println("--------------------");
        while (node2 != null){
            System.out.print(node2.value);
            node2 = node2.last;
        }
    }
    public static DoubleNode reverseList(DoubleNode head){
        DoubleNode pre = null, cur = head, post = null;
        while (cur != null){
            post = cur.next;
            cur.next = pre;
            cur.last = post;
            pre = cur;
            cur = post;
        }
        return pre;
    }


}

你可能感兴趣的:(数据结构与算法)