反转链表-循环+递归

题目描述:定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

解决方法1:双指针+循环
定义cur结点,用来指向当前结点的下一个结点。
定义pre结点,用来作为新的链表的下一个结点。

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null) return head;
        ListNode pre = null;
        while(head != null){
            ListNode cur = head.next;
            head.next = pre;
            pre = head;
            head = cur;
        }
        return pre;
    }
}

解决方法2:递归

class Solution {
    public ListNode reverseList(ListNode head) {
    	if(head == null) return head; 
        return reverse(head);
    }

    public ListNode reverse(ListNode cur) {
        if (cur.next == null) return cur;   // 原链表的尾节点作为已反转链表的头节点,往回传递
        ListNode nxt = reverse(cur.next);   // 获得已反转链表的头节点
        cur.next.next = cur;                // 使cur的后继(已反转链表的尾节点)指向cur
        cur.next = null;                    // 此时cur成为了已反转链表的尾节点,使cur指向null
        return nxt;                         // 往回传递已反转链表的头节点
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值