zoukankan      html  css  js  c++  java
  • 【C/C++】链表

    #include <bits/stdc++.h>
    using namespace std;
    
    struct node
    {
        int data; // 数据
        node* next; // 指针
    };
    
    node* create(int Array[])
    {
        node *p, *pre, *head; // head头节点, pre当前节点的前驱节点,p当前节点
        head = new node;
        head->next = NULL;
        pre = head;
        for (int i = 0; i < 5; i++)
        {
            // 创建新节点
            p = new node;
            // 将Array[i]赋给新建的节点作为数据域,也可以scanf输入
            p->data = Array[i];
            p->next = NULL;
            pre->next = p;
            // 更新
            pre = p;
        }
        return head;
    }
    
    int search(node* head, int x)
    {
        int count = 0;
        node* p = head->next;
        while (p != NULL)
        {
            if(p->data == x)
            {
                count++;
            }
            p = p->next;
        }
        return count;
    }
    
    void insert(node* head, int pos, int x)
    {
        node* p = head; // 保护头指针
        // 找到位置
        for(int i = 0; i < pos - 1; i++)
        {
            p = p->next; // pos - 1是为了找到位置的前一个节点
        }
        node* q = new node;
        q->data = x;
        q->next = p->next;
        p->next = q;
    }
    
    void del(node* head, int x)
    {
        node* p = head->next;
        node* pre = head;
        while(p != NULL)
        {
            if(p->data == x)
            {
                pre->next = p->next;
                delete(p);
    
            }
            else
            {
                pre = p;
                p = p->next;
            }
            
        }
    }
    
    int main()
    {
        int Array[5] = {5, 3, 6, 1, 2};
        node* L = create(Array);
        L = L->next;
        while(L != NULL)
        {
            printf("%d", L->data);
            L = L->next;
        }
        system("pause"); 
    }
    
  • 相关阅读:
    poj3167
    poj2752 bzoj3670
    poj2886
    poj3294
    [luoguP2564][SCOI2009]生日礼物(队列)
    [luoguP1866]滑动窗口(单调队列)
    [luoguP1198][JSOI2008] 最大数(线段树 || 单调栈)
    [HDU4348]To the moon(主席树)
    [luoguP1168]中位数(主席树+离散化)
    [HDU4417]Super Mario(主席树+离散化)
  • 原文地址:https://www.cnblogs.com/kinologic/p/14702058.html
Copyright © 2011-2022 走看看