單鏈表的插入刪除操作(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;

}
發佈了64 篇原創文章 · 獲贊 29 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章