#include <iostream>
#include <stdlib.h>
#include <stdbool.h>
using namespace std;
//结点
class Node
{
public:
int data;
Node* next;
Node(int d)
{
data = d;
next = NULL;
}
};
//链表
class List
{
Node* head;
public:
List()
{
head =NULL;
}
void init(Node *p)
{
head = p;
}
//插入
void insert(Node* p)
{
p -> next = head;
head = p;
}
//删除
Node* delete_node(Node* p)
{
Node** pnext;
for(pnext = &head;*pnext;pnext = &(*pnext) ->next)
{
if(*pnext == p)
{
*pnext = p -> next;
return p;
}
}
return NULL;
}
//遍历链表
/*void trave_list(Node* p)
{
for(p = head;p;p = p ->next)
{
cout<< p->data << endl;
}
}*/
//查找
Node* search_list(int key)
{
Node* p;
p =head;
while(p)
{
if(p->data == key)
{
cout << "----" << p->data << "----" << endl;
return p;
}
p = p->next;
}
return NULL;
}
//销毁链表
void destroy()
{
Node* p;
Node* q;
for(p = head;p;)
{
q = p -> next;
delete p;
p = q;
}
head = NULL;
}
friend ostream& operator << (ostream& os,List& list);
};
//遍历并打印
ostream& operator << (ostream& os,List& list)
{
Node *p;
for(p = list.head;p;p = p ->next)
{
cout<< p->data << " ";
}
return os;
}
int main()
{
List list;
Node *p;
for(int i =0;i<10;i++)
{
p = new Node(i);
list.insert(p);
}
p = list.search_list(5);//在链表中找到结点
Node* t = list.delete_node(p);//把结点移除
list.delete_node(t);//释放结点空间
//list.trave_list(p);
cout<< list << endl;//遍历并打印
list.destroy();//销毁
return 0;
}