链表

链表

  1. 链表结构定义

    // 链表结构定义
    typedef struct LNode{
        int data;
        struct LNode* next;
    }LNode, *LinkList;
    
  2. 初始化链表

    // 初始化链表
    bool InitList(LinkList &L){
        L = new LNode;
        L->next = nullptr;
        return true;
    }
    
  3. 创建链表(头插法)

    // 创建链表(头插法)
    void CreatListHeadInsert(LinkList &L){
        cout << "请输入要插入的元素个数"  << endl;
        int n;
        cin >> n;
        while(n--) {
            int t;
            cin >> t;
            LNode* p = new LNode;   // new一个待插入的新节点
            p->data = t;
            p->next = L->next;
            L->next = p;
        }
    }
    
  4. 创建链表(尾插法)

    // 创建链表(尾插法)
    void CreatListTailInsert(LinkList &L){
        LNode *tail = L;        // 尾指针
        cout << "请输入要插入的元素个数"  << endl;
        int n;
        cin >> n;
        while(n--) {
            int t;
            cin >> t;
            LNode* p = new LNode;
            p->data = t;
            tail->next = p;
            tail = p;
        }   
        tail->next = nullptr;
    }
    
  5. 遍历链表

    // 遍历链表
    void ListShow(const LinkList &L){
        LNode* p = L->next;
        while(p != nullptr){
            cout << p->data << " ";
            p = p->next;
        }
        cout << endl;
    }
    
  6. 求表长

    // 求表长
    int Length(const LinkList &L){
        int len = 0;
        LNode *p = L;
        while(p->next != nullptr){
            p = p->next;
            len++;
        }
        return len;
    }
    
  7. 插入节点

    // 插入节点
    bool ListInsert(LinkList &L, int i, int e){
        LNode *p = L;
        int j = 0;
        while(p != nullptr && j < i - 1){
            p = p->next;
            j++;
        }
        if(p == nullptr) return false;  // i越界(也可提前判断)
    
        LNode* s = new LNode;
        s->data = e;
        s->next = p->next;
        p->next = s;
        return true;
    }
    
  8. 删除节点

    // 删除节点
    bool LisetDelete(LinkList &L, int i, int e){
        LNode *p = L;
        int j = 0;
        while(p != nullptr && j < i - 1){
            p = p->next;
            j++;
        }
        // i的值非法
        if(p == nullptr || p->next == nullptr) 
            return false;
        LNode *q = p->next;
        p->next = q->next;
        delete q;
        return true;
    }
    
  9. 销毁链表

    // 销毁链表
    bool DestoryList(LinkList &L){
        if(L == nullptr) return false;
    
        LNode *p;
        while(L != nullptr){
            p = L->next;
            delete L;
            L = p;
        }
        return true;
    }
    
  10. 链表逆置

    // 链表逆置
    bool ListReverse(LinkList &L){
        if(L->next == nullptr) return false;
        LNode *p = L->next, *q;
        L->next = nullptr;      // L置空
        while(p != nullptr){
            q = p->next;
            p->next = L->next;  // 头插转置
            L->next = p;
            p = q;
        }
        return true;
    }
    
posted @ 2024-04-05 11:20  ZhangFirst1  阅读(15)  评论(0)    收藏  举报