zoukankan      html  css  js  c++  java
  • 链表

    #include <iostream>
    using namespace std;

    struct MyList
    {
        int data;
        MyList*next;
    };

    void Init(MyList&head)
    {
        head.data=0;
        head.next=NULL;
    }
    void ListInsert(MyList&head,int i,int data)
    {
        int j=1;
        MyList*p,*s;
        p=&head;
        while(p&&j<i)
        {
            p=p->next;
            j++;
        }
        if(!p||j>i)
        {
            return;
        }
        s=new MyList();
        s->data=data;
        s->next=p->next;
        p->next=s;
    }

    void update(MyList&head,int i,int data)
    {
        int j=1;
        MyList*p=&head;
        while(p)
        {
            p=p->next;
            if(j==i)
            {
                break;
            }
            j++;
        }
        if(!p||j>i)
        {
            return;
        }
        p->data=data;
    }

    void del(MyList&head,int i)
    {
        int j=1;
        MyList*p=&head;
        MyList*s;
        while(p&&j<i)
        {
            p=p->next;
            j++;
        }
        if(!p||j>i)
        {
            return;
        }
        s=p->next;
        p->next=s->next;
        delete s;
    }

    int query(MyList&head,int i,int *e)
    {
        int j=1;
        MyList*p=&head;
        while(p)
        {
            p=p->next;
            if(j==i)
            {
                break;
            }
            j++;
        }
        if(!p||j>i)
        {
            return -1;
        }
        *e=p->data;
        return 0;
    }

    void show(MyList head)
    {
        MyList* p=head.next;
        while(p!=NULL)
        {
            cout<<p->data<<endl;
            p=p->next;
        }
    }

    int main()
    {
        MyList head;
        Init(head);
        for(int i=0;i<10;i++)
        {
            ListInsert(head,i+1,20+i);
        }
        cout<<"update"<<endl;
        update(head,5,200);
        show(head);
        del(head,1);
        cout<<"delete"<<endl;
        show(head);
        cout<<"query"<<endl;
        int result=0;
        query(head,2,&result);
        cout<<result<<endl;
        cin.get();
        
    }

  • 相关阅读:
    按需导入NavMenu无法使用情况解决办法
    如果要使用另一台电脑作为服务器,注意关掉防火墙
    mongoose学习
    koa2的学习
    vue中swiper的使用
    447. Number of Boomerangs
    33. Search in Rotated Sorted Array
    461. Hamming Distance
    392. Is Subsequence
    412. Fizz Buzz
  • 原文地址:https://www.cnblogs.com/cppfans140812/p/5816257.html
Copyright © 2011-2022 走看看