单链表的插入删除操作(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;

}
原文地址:https://www.cnblogs.com/yxwkf/p/5149492.html