链表(C++实现)

来源:互联网 发布:淘宝助理5老版本下载 编辑:程序博客网 时间:2024/05/22 06:54

上一篇试用C风格写的链表,这次是C++语法下的


#include <iostream>
using namespace std;

//Node 类
class Node
{
public:
Node* next;
int data;


Node(void)
{
next = NULL;
data = 0;
}


Node(int value)
{
data = value;
next = NULL;
}


~Node(void)
{

}

};

//链表类
class List
{
public:
List() {};  
~List() {};


bool AddNode(int value);    //声明增加节点成员函数
bool FindNode(int value);   //查找
bool DeleteNode(int value);  //删除
bool UpdateNode(int value1, int value2);//修改
bool DestroyList();//删除
bool output();//输出


private:
Node head;
};


//查找
bool List::FindNode(int value)
{
if (NULL == head.next)
{
cout << "List NULL" << endl;
return false;
}
Node* cur = head.next;
while (value != cur->data)
{
if (NULL == cur->next)
{
cout << "No this data" << endl;
return false;
}
cur = cur->next;
}
cout << cur->data << endl;
return true;
}


//添加
bool List::AddNode(int value)
{
Node* node = new Node(value);
if (NULL == node)
{
return false;
}
//node->setvalue(value);


Node* cur = &head;
while (NULL != cur->next)
{
cur = cur->next;
}
cur->next = node;
return true;
}


//删除节点
bool List::DeleteNode(int value)
{
if (NULL == head.next)
{
cout << "List NULL" << endl;
return false;
}
Node* cur = head.next;
Node* pre = (Node*)&head;
while (value != cur->data)
{
if (NULL == cur->next)
{
cout << "NO this value" << endl;
return false;
}
pre = cur;
cur = cur->next;
}
pre->next = cur->next;
delete cur;
return true;
}


//修改
bool List::UpdateNode(int value1, int value2)
{
if (NULL == head.next)
{
cout << "List NULL" << endl;
return false;
}
Node* cur = head.next;
while (value1 != cur->data)
{
if (NULL == cur->next)
{
cout << "No this data" << endl;
return false;
}
cur = cur->next;
}
cur->data = value2;
return true;
}


//销毁链表
bool List::DestroyList()
{
if (NULL == head.next)
{
return true;
}
Node* cur = head.next;
while (NULL != cur->next)
{
Node* tem = cur;
cur = cur->next;
delete tem;
}
head.next = NULL;
return true;
}


//输出链表
bool List::output()
{
if (NULL == head.next)
{
cout << "List NULL" << endl;
return false;
}


Node* cur = head.next;
while (NULL != cur)
{
cout << ' ' << cur->data;
cur = cur->next;
}
cout << endl;
return true;
}


int main()
{
List list;
list.AddNode(10);
list.AddNode(20);
list.output();


list.UpdateNode(40, 50);
list.output();
list.UpdateNode(10, 30);
list.output();


list.FindNode(10);
list.FindNode(20);


list.DeleteNode(10);
list.output();
list.DeleteNode(20);
list.output();


list.DestroyList();
list.output();
getchar();
return 0;
}

0 0
原创粉丝点击