做题总结 206. 反转链表

文章介绍了如何使用C++和Java分别通过数组法、迭代法和递归法来反转链表。数组法虽然直观但空间消耗大;迭代法利用指针操作实现,代码简洁;递归法展示了通过调用自身处理子问题的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数组法(C++)

遍历链表,把结点的值存储在vector中,然后重新创建链表。
缺点:大量空间浪费

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        vector<int> nums;
        ListNode* p = head;
        while(p != nullptr) {
            nums.push_back(p->val);
            p = p->next;
        }

        ListNode* rhead = new ListNode();
        p = rhead;
        for(int i=nums.size()-1; i>=0; i--) {
            ListNode* temp = new ListNode(nums[i]);
            p->next = temp;
            p = temp;
        }
        return rhead->next;
    }
};

迭代法(Java)

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

        ListNode t1 = null;
        ListNode t2 = head;
        ListNode temp;
        while(t2!=null) {
            temp = t2.next;//她的位置
            t2.next = t1;

            t1=t2;
            t2=temp;
        }
        return t1;

    }
}

递归法

这里是官网的示范,看不懂!!

class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值