反转单向双向链表

Posted 数据科学工作加油站

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了反转单向双向链表相关的知识,希望对你有一定的参考价值。

要求:如果链表长度为N,时间复杂度要求为O(N),额外的空间复杂度要求为O(1)

public class Problem04_ReverseList {
    
//    单链表数据结构
    public static class Node {
        public int value;
        public Node next;
        
        public Node(int data) {
            this.value = data;
        }
    }
    
//    逆序单链表函数
    public static Node reverseList(Node head) {
        Node pre = null;
        Node next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre ;
    }

//    双链表数据结构
    public static class DoubleNode {
        public int value;
        public DoubleNode next;
        public DoubleNode last;
        
        public DoubleNode(int data) {
            this.value = data;
        }
    }

// 逆序双链表函数
    public static DoubleNode reverseList(DoubleNode head) {
        DoubleNode pre = null;
        DoubleNode next = null;
        
        while (head != null) {
            next = head.next;
            head.next = pre;
            head.last = next;
            pre = head;
            head = next;
        }
        return pre;
    }
    
// 打印单链表中的数据
    public static void printLinkedList(Node head) {
        System.out.println("LinkedList: ");
        while (head != null) {
            System.out.println(head.value + " ");
            head = head.next;
        }
        System.out.println();
    }
    
//  打印双链表中的数据
    public static void printDoubleLinkedList(DoubleNode head) {
        System.out.println("DoubleLinkedList: ");
        DoubleNode end = null;
        while (head != null) {
            System.out.println(head.value + " ");
            head = head.next;
        }
        System.out.println(" | ");
        while (end != null){
            System.out.println(end.value + " ");
            end = end.last;            
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
        Node head1 = new Node(1);
        head1.next = new Node(2);
        head1.next.next = new Node(3);
        printLinkedList(head1);
        head1 = reverseList(head1);
        printLinkedList(head1);

        DoubleNode head2 = new DoubleNode(1);
        head2.next = new DoubleNode(2);
        head2.next.last = head2;
        head2.next.next = new DoubleNode(3);
        head2.next.next.last = head2.next;
        head2.next.next.next = new DoubleNode(4);
        head2.next.next.next.last = head2.next.next;
        printDoubleLinkedList(head2);
        printDoubleLinkedList(reverseList(head2));

    }

}

运行结果:

LinkedList: 
1 
2 
3 

LinkedList: 
3 
2 
1 

DoubleLinkedList: 
1 
2 
3 
4 
 | 

DoubleLinkedList: 
4 
3 
2 
1 
 |

以上是关于反转单向双向链表的主要内容,如果未能解决你的问题,请参考以下文章

算法总结之 反转单向和双向链表

[算法]反转单向链表和双向链表

反转单向双向链表

C语言反转单向链表的代码

反转单链表和双链表

如何链表反转