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

}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值