代码随想录算法训练营第三天 |链表

链表

一、定义与方法

使用结构体

// 单链表
struct ListNode {
    int val;  // 节点上存储的元素
    ListNode *next;  // 指向下一个节点的指针
    ListNode(int x) : val(x), next(NULL) {}  // 节点的构造函数
};

使用类

class LNode {
public:
    int val;
    LNode *next;

    LNode(int x) : val(x), next(nullptr) {}
};

class LinkedList {
private:
    LNode *head;
public:
    LinkedList() : head(nullptr) {}
    
    void append(int data) {
        LNode *newNode = new LNode(data);
        if (head == nullptr){
            LNode* dummyHead = new LNode(0);
            head=dummyHead;
            head->next= newNode;
        } 
        else{
            LNode *cur = head;
            while (cur->next!= nullptr)
                cur=cur->next;
            cur->next = newNode;
        }
    }
    
    void printList(){
        LNode *cur = head->next;
        while(cur!=nullptr){
            std::cout << cur->val;
            cur=cur->next;
            if(cur==nullptr) std::cout<< std::endl;
            else cout <<" ";
        }
    }

    int len(){
        LNode *cur = head->next;
        int n=0;
        while(cur!=nullptr){
            cur=cur->next;
            n++;
        }
        return n;
    }
    
    void insert(int pos,int data){
        if(pos>len()||pos<1)
            cout<<"Insertion position is invalid."<<endl;
        else{
            LNode *newNode = new LNode(data);
            LNode *cur = head,*pre;
            while(pos--){
                pre = cur;
                cur = cur->next;
            }
            newNode->next=cur;
            pre->next = newNode;
            printList();   
        }
    }
    void deleteL(int pos){
        if(pos<1||pos>len())
            cout<<"Deletion position is invalid."<<endl;
        else{
            LNode *cur = head,*pre;
            while(pos--){
                pre=cur;
                cur=cur->next;
            }
            pre->next = cur->next;
            printList();
        }
    }
};

二、相关题目

203.移除链表元素

题目链接

注意:
1.使用虚拟头节点方便操作
2.注意移除节点后删除内存(包括虚拟头节点)

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode *dummyhead = new ListNode(0);
        dummyhead->next = head;
        ListNode *cur = dummyhead;
        while(cur->next!=nullptr){
            if(cur->next->val==val){
                ListNode *tem = cur->next;
                cur->next=tem->next;
                delete tem;
            }else cur=cur->next;
        }
        head=dummyhead->next;
        delete dummyhead;
        return head;
    }
};

707.设计链表

题目链接

类的初始化中,使用私有变量来记录长度和虚拟节点

private:
    int _size;
    LinkedNode * _dummyhead;
};
MyLinkedList() {
        _size = 0;
        _dummyhead = new LinkedNode(0);
    }

删除节点后将tmp指向nullptr

		delete tmp;
        //delete命令指示释放了tmp指针原本所指的那部分内存,
        //被delete后的指针tmp的值(地址)并非就是NULL,而是随机值。也就是被delete后,
        //如果不再加上一句tmp=nullptr,tmp会成为乱指的野指针
        //如果之后的程序不小心使用了tmp,会指向难以预想的内存空间
        tmp=nullptr;

完整代码

class MyLinkedList {

public:
    // 定义链表节点结构体
    struct LinkedNode {
        int val;
        LinkedNode* next;
        LinkedNode(int val):val(val), next(nullptr){}
    };

    MyLinkedList() {
        _size = 0;
        _dummyhead = new LinkedNode(0);
    }
    
    int get(int index) {
        if(index>(_size-1)||index<0) return -1;
        LinkedNode *cur=_dummyhead->next;
        while(index--)
        {
            cur=cur->next;
        }
        return cur->val;
    }
    
    void addAtHead(int val) {
        LinkedNode *newLNode = new LinkedNode(val);
        newLNode->next = _dummyhead->next;
        _dummyhead->next = newLNode;
        _size++;
    }
    
    void addAtTail(int val) {
        LinkedNode *newLNode = new LinkedNode(val);
        LinkedNode *cur=_dummyhead;
        while(cur->next!=nullptr){
            cur=cur->next;
        }
        newLNode->next = cur->next;
        cur->next = newLNode;
        _size++;
    }
    
    void addAtIndex(int index, int val) {
        if(index>_size||index<0)return;
        LinkedNode *newLNode = new LinkedNode(val);
        LinkedNode *pre=_dummyhead;
        while(index--){
            pre=pre->next;
        }
        newLNode->next = pre->next;
        pre->next = newLNode;
        _size++;

    }
    
    void deleteAtIndex(int index) {
        if(index<0||index>(_size-1)) return;
        LinkedNode *pre=_dummyhead,*tem;
        while(index--){
            pre=pre->next;
        }
        tem=pre->next;
        pre->next=tem->next;
        delete tem;
        _size--;

    }
private:
    int _size;
    LinkedNode * _dummyhead;
};

206.反转链表

题目链接
第一版

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        // 原地逆置
        if (head == nullptr)
            return head;
        else {
            ListNode* dummyNode = new ListNode(0);
            ListNode *cur = head, *nex;
            while (cur!= nullptr) {
                nex = cur->next;
                cur->next = dummyNode->next;
                dummyNode->next = cur;
                if(nex==nullptr)break;
                else{
                    cur = nex;
                    nex = nex->next;
                }
            }
            cur = dummyNode->next;
            delete dummyNode;
            return cur;
        }
    }
};

缺点: 虚拟头节点

改进方法1: 双链表法
时间复杂度 : O ( n ) O(n) O(n)
空间复杂度 : O ( 1 ) O(1) O(1)

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* temp; // 保存cur的下一个节点
        ListNode* cur = head;
        ListNode* pre = NULL;
        while(cur) {
            temp = cur->next;  // 保存一下 cur的下一个节点,因为接下来要改变cur->next
            cur->next = pre; // 翻转操作
            // 更新pre 和 cur指针
            pre = cur;
            cur = temp;
        }
        return pre;
    }
};

其余方法:递归法
时间复杂度 : O ( n ) O(n) O(n)
空间复杂度 : O ( n ) O(n) O(n)

class Solution {
public:
	//方法1
    ListNode* reverse(ListNode* pre,ListNode* cur){
        if(cur == NULL) return pre;
        ListNode* temp = cur->next;
        cur->next = pre;
        // 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步
        // pre = cur;
        // cur = temp;
        return reverse(cur,temp);
    }
    ListNode* reverseList1(ListNode* head) {
        // 和双指针法初始化是一样的逻辑
        // ListNode* cur = head;
        // ListNode* pre = NULL;
        return reverse(NULL, head);
    }
    //方法2
	ListNode* reverseList2(ListNode* head) {
        // 边缘条件判断
        if(head == NULL) return NULL;
        if (head->next == NULL) return head;
        
        // 递归调用,翻转第二个节点开始往后的链表
        ListNode *last = reverseList(head->next);
        // 翻转头节点与第二个节点的指向
        head->next->next = head;
        // 此时的 head 节点为尾节点,next 需要指向 NULL
        head->next = NULL;
        return last;
    }

};
### 代码随想录训练营第37期介绍 #### 报名方式 对于希望参与代码随想录训练营第37期的学习者而言,报名流程相对简便。通常情况下,可以通过官方网站或官方指定的合作平台完成注册并支付费用以获得参加资格。此外,在线填写个人信息表单也是必不可少的一部分,这有助于主办方更好地了解学员背景以便提供个性化指导和支持[^2]。 #### 课程内容概述 该训练营旨在帮助参与者深入理解算法设计的核心概念和技术,并通过实战练习提高编程能力。具体来说: - **基础巩固阶段**:此部分专注于夯实数据结构基础知识,如数组、链表、栈队列等基本操作及其应用场景;同时也会涉及一些简单而常见的算法模式,比如贪心法、回溯法等。 - **专题强化模块** - 对于像二分查找这样的经典问题进行了细致讲解[L.C.704],不仅限于标准实现方法的教学,更鼓励探索多种可能的解决方案来拓宽思维视野; - 针对动态规划这类较难掌握的内容,则会采用由浅入深的方式逐步引导学生构建起完整的理论框架,并配合大量实例演练加深记忆点; - 还有图论方面的重要知识点覆盖,包括但不限于最短路径计算、最小生成树求解等内容。 - **项目实践环节** 为了使所学知识能够真正转化为实际工作中的生产力,特别设置了基于真实场景下的综合型开发任务作为结业考核之一。这些项目往往围绕当下热门领域展开,例如人工智能、大数据处理等前沿方向,让每位成员都能亲身体验到从构思创意到最后产品发布的全过程。 ```python def binary_search(nums, target): left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid] < target: left = mid + 1 elif nums[mid] > target: right = mid - 1 else: return mid return -1 ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值