• leetcode206. 反转链表


    1:迭代法

    假设存在链表 1 → 2 → 3 → Ø,我们想要把它改成 Ø ← 1 ← 2 ← 3。

    在遍历列表时,将当前节点的 next 指针改为指向前一个元素。由于节点没有引用其上一个节点,因此必须事先存储其前一个元素。在更改引用之前,还需要另一个指针来存储下一个节点。不要忘记在最后返回新的头引用!

    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
        ListNode *pre=NULL;
        ListNode *curr=head;
        while(curr!=NULL)
        {
            ListNode *temp=curr->next;
            curr->next=pre;
            pre=curr;
            curr=temp;
        }
        return pre;  
        }
            
    };

    2 递归

    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
        
        if (head == NULL || head->next == NULL) return head;
        ListNode* p=reverseList(head->next);
        head->next->next=head;
        head->next=NULL;
        return p;
        }
            
    };
  • 相关阅读:
    dracut-initqueue timeout
    Request.Url
    ipv4 ipv6数据库存储
    DataRow To DataTable
    AS ShortCut
    linq on 多链接条件
    SQL逻辑查询语句执行顺序
    ckeditor 使用几点
    SqlDataAdapter 更新插入 与 InsertBulkCopy
    HTTP协议改HTTPS
  • 原文地址:https://www.cnblogs.com/renzmin/p/11877186.html
Copyright © 2020-2023  润新知