Reverse a LinkedList 链表倒置

两种方法倒置一个链表

1. 递归

亮点在于构建一个假的head:newHead,代码如下:

class RecursivelyReverseLinkedList{
    ListNode newHead = new ListNode(0);
    public ListNode reverseList(ListNode head) {
        if(head == null) {
            return null;
        } // empty list
        reverseList(newHead, head); // recursion
        return newHead.next;
    }

    public ListNode reverseList(ListNode head, ListNode p) {
        head.next = p; // connect the head and the list
        if(p.next != null) {
            ListNode p1 = new ListNode(0); // new head
            ListNode q = reverseList(p1, p.next); // get the last non empty node
            p.next = null; // to put the p in new list
            q.next = p; // connect 
            head.next = p1.next; // connect
        } 
        return p; // return the last non empty node
    }
}

2. 迭代

    public ListNode reverseList(ListNode head) {
        if(head == null) {
            return null;
        } // return empty list
        ListNode newHead = new ListNode(0); // new head
        ListNode p = head; // temp index
        while(p != null) {
            ListNode temp = p; // get off the first node
            p = p.next; // move to next node
            temp.next = newHead.next; // connect
            newHead.next = temp;
        }
        return newHead.next; // return the right head
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值