zoukankan      html  css  js  c++  java
  • 单链表的插入删除操作(c++实现)

    下列代码实现的是单链表的按序插入、链表元素的删除、链表的输出

    //  mylink.h 代码
    #ifndef MYLINK_H
    #define MYLINK_H
    #include<iostream>
    using namespace std;
    struct node
    {
      int data;
      node *next;
    };
    
    class list
    {
    public:
        list()
        {
         head=NULL;
        };
        void insert(int item);
        void del(int item);
        void show();
    private:
        node *head;
    };
    
    
    void list::insert(int item) //按序插入
    {
        node *p=new node();
        p->data=item;
        p->next=NULL;
        if(head==NULL) //当链表为空时
        {
          head=p;    
        }
        else 
        {   
          node *q,*r;
          q=head;
          while(q&&q->data<=p->data)
            {
              r=q;
              q=q->next;
             }
           if(q!=NULL)
           {
              p->next=q;
              r->next=p;
           }
           else
           {
              p->next=NULL;
              r->next=p;
           }
        }
    }
    void list::del(int item)
    {
      if(head==NULL)
      {
      cout<<"链表为空,不能删除"<<endl;
      }
      else if(head->data==item)
      {
        head=head->next;
      }
      else
      { 
       int flag=1;
       while(flag)   //保证删除链表中全部值为item的数据 
       {
         node *p=head;
         node *q;
         while(p&&p->data!=item)
         {  
           q=p;
           p=p->next;
          }
         if(p) //在链表中找到该元素
          q->next=p->next;
         else    
          flag=0;
       }
      }
    }
    void list::show()
    {
      node *p;
      p=head;
      if(head==NULL)
      {
       cout<<"链表为空"<<endl;
      }
      else
      {
        cout<<"单链表为:";
        while(p)
        {
         cout<<p->data<<" ";
         p=p->next;
        }
        cout<<endl;
      }
    }
    #endif
    
    

    主程序

    //  main.cpp 代码
    #include "mylink.h"
    #include<iostream>
    using namespace std;
    int main()
    {
      list L;
      L.insert(1);
      L.insert(3);
      L.insert(2);
      L.insert(5);
      L.insert(2);
      L.insert(3);
      L.show();
      L.del(2);
      cout<<"删除元素2后:"<<endl;
      L.show();
      L.del(3);
      cout<<"删除元素3后:"<<endl;
      L.show();
      cout<<"OK"<<endl;
      system("pause");
      return 0;
    
    }
  • 相关阅读:
    【动态规划】最长公共子序列与最长公共子串
    【图论】深入理解Dijsktra算法
    webSocket基本知识
    React的合成事件
    mobx的实现原理
    js自定义事件
    React16废弃的生命周期和新的生命周期
    正则表达式基本概念
    webpack异步加载文件的方式
    React.lazy懒加载组件
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5149492.html
Copyright © 2011-2022 走看看