链表反转

package com.mashibing.drools;

public class MainClass3 {
    public static void main(String[] args) {
        Nodes head1 = init();
        head1 = revert(head1);
        print(head1);
    }

    private static Nodes revert(Nodes head) {
        Nodes pre = null;
        Nodes next = null;
        while (head != null) {
            next=head.next;
            head.next=pre;
            pre=head;
            head=next;
        }
        return pre;
    }

    private static void print(Nodes head) {
        while (head != null) {
            System.out.print(head.data + "\t");
            head = head.next;
        }
    }

    private static Nodes init() {
        Nodes head = new Nodes(1);
        Nodes head2 = new Nodes(2);
        Nodes head3 = new Nodes(3);
        Nodes head4 = new Nodes(4);
        head.next = head2;
        head2.next = head3;
        head3.next = head4;
        return head;
    }
}
posted @ 2021-06-22 16:27  庭有奇树  阅读(26)  评论(0编辑  收藏  举报