单链表逆转

public class Solution {
    static class Node {
        char data;
        Node next;

        public Node() {
        }

        public Node(char data, Node next) {
            this.data = data;
            this.next = next;
        }
    }

    public static Node init() {

        Node n5 = new Node('E', null);
        Node n4 = new Node('D', n5);
        Node n3 = new Node('C', n4);
        Node n2 = new Node('B', n3);
        Node n1 = new Node('A', n2);
        return n1;
    }

    public static Node reverse(Node head) {
        Node curr = head;
        Node pre = null;
        while (curr != null) {
            Node next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }

    public static Node reverse2(Node head) {
        Node dummyHead = new Node();
        Node p = head;
        while (p != null) {
            Node q = p.next;
            p.next = dummyHead.next;
            dummyHead.next = p;
            p = q;
        }
        return dummyHead.next;
    }

    public static Node reverse3(Node head) {
        if (head == null || head.next == null) {
            return head;
        }
        Node newHead = reverse3(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    public static void print(Node head) {
        while (head != null) {
            System.out.print(head.data + " ");
            head = head.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        print(reverse(init()));
        print(reverse2(init()));
        print(reverse3(init()));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值