单链表和双向链表的反转

单链表和双向链表的反转

  • 单链表的反转
  • 双向链表的反转
  • 实现代码

单链表的反转

单链表的反转主要是利用两个辅助的结点pre 和 next 分别代表当前要处理的节点的前一个结点和后一个结点,然后通过改变结点的next域的指向来反转整个链表,通过循环处理,每次反转一个之后,pre指向下一个结点,也就是head,head更改为head的下一个结点,也就是next,这样直到head为空,返回pre就反转了整个单链表,可以看一下下面的两个步骤
这里写图片描述

双向链表反转

和单链表区别不大,不过要注意反转的时候,head的pre域要指向next,因为双向链表的任意一个结点要同时有前驱和后继,所以这里要同时给出head的pre和next域,可以参考下图。
这里写图片描述

实现代码

/**
 * 反转单向链表和双向链表
 * 这里写的是不带头结点的 (改成带头结点的不难) (带头结点的就是第一个节点一般没有数据域(插入删除的时候比不带头结点的方便))
 */
public class ReverseList {

    private static class Node{
        public int value;
        public Node next;

        public Node(int value) {
            this.value = value;
        }
    }

    //翻转单向链表 (不带头结点)
    public static Node reverseList(Node head){
        Node pre = null;
        Node next = null;
        while(head != null){
            next = head.next; //记录原先的下一个结点
            head.next = pre;  //指向前一个结点 ,如果是第一个,那么前一个结点就是null
            //进行下一次的循环
            pre = head;
            head = next;
        }
        return pre; //这个时候head = null head的前一个就是头结点了
    }

    //打印单向链表
    public static void printList(Node head){
        Node node = head;
        while(node != null){
            System.out.print(node.value + " ");
            node = node.next;
        }
        System.out.println();
    }



    private static class DoubleNode{
        public int value;
        public DoubleNode pre;
        public DoubleNode next;

        public DoubleNode(int value) {
            this.value = value;
        }
    }

    public static DoubleNode reverseList(DoubleNode head){
        DoubleNode pre = null;
        DoubleNode next = null;
        while(head != null) {
            next = head.next;
            head.next = pre;
            head.pre = next;
            pre = head;
            head = next;
        }
        return pre;
    }

    //打印单向链表
    public static void printDoubleList(DoubleNode head){
        DoubleNode node = head;
        while(node != null){
            System.out.print(node.value + " ");
            node = node.next;
        }
        System.out.println();
    }


    public static void main(String[] args) {
        //测试单链表 1 2 3
        Node head1 = new Node(1);
        head1.next = new Node(2);
        head1.next.next = new Node(3);
        printList(head1);
        head1 = reverseList(head1);
        printList(head1);


        //测试双向链表  1 2 3 4
        DoubleNode head2 = new DoubleNode(1);
        head2.next = new DoubleNode(2);
        head2.next.pre = head2;

        head2.next.next = new DoubleNode(3);
        head2.next.next.pre= head2.next;

        head2.next.next.next = new DoubleNode(4);
        head2.next.next.next.pre = head2.next.next;

        printDoubleList(head2);
        printDoubleList(reverseList(head2));
    }
}

测试结果
这里写图片描述

猜你喜欢

转载自blog.csdn.net/zxzxzx0119/article/details/81073246