单链表的封装

#include <iostream>
using namespace std;

typedef struct Node
{
  int m_data;
  Node *m_next;
}Node;

class IntList
{
public:
 IntList();
 ~IntList();
 bool append(int value);
 bool remove(int value);
 void printList();
 Node *find(int value);
private:
 Node *m_head;
};

IntList::IntList()//构造
{
  m_head = new Node;//空头结点
  m_head->m_next = NULL;
}

IntList::~IntList()//析构
{
   Node *p = m_head;
   while(p!=NULL)
   {
    Node *temp = p;
    p = p->m_next;
    delete temp;
   }
}

bool IntList::append(int value)//尾部添加
{
   Node * temp = new Node;
   if(temp==NULL)
   {
   return false;
   }
   Node *p = m_head;
   while(p->m_next!=NULL)
   {
   p = p->m_next;
   }
   temp->m_data = value;
   temp->m_next = p->m_next;
   p->m_next = temp;
   return true;
}

bool IntList::remove(int value)//删除
{
  Node * pre = m_head;
  Node * p = m_head->m_next;
  if(p == NULL)
   return false;
  while(p->m_data!=value&&p->m_next!=NULL)
  {
    pre = p;
    p = p->m_next;
  }
  if(p->m_data == value)
  {
     pre ->m_next = p->m_next;
  delete p;
  }
  else
  {
   return false;
  }
  return true;
}

void IntList::printList()//打印
{
 Node *p = m_head->m_next;
 while(p!=NULL)
 {
  cout<<p->m_data<<' ';
  p = p->m_next;
 }
 cout<<endl;
}

Node *IntList::find(int value)//查找
{
 Node *p = m_head->m_next;
 if(p==NULL)
 {
  return NULL;
 }
    while(p->m_data!= value&&p->m_next!=NULL)
 {
      p = p->m_next;
 }
 if(p->m_data == value)
 {
  return p;
 }
 else
 {
  return NULL;
 }
}
int main(int argc, char* argv[])
{
 IntList L;
 L.append(10);
 L.append(13);
 L.append(8);
    L.append(6);
 L.printList();
 L.remove(8);
    L.printList();
 Node * f = L.find(10);
 if(f==NULL)
 { 
  cout<<"NULL"<<endl;
 }
 else
 {
 cout<<f<<'\t'<<f->m_data<<endl;
 }

 return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值