用C++编线性表的定义 插入 删除
1个回答
展开全部
class LinkList{
private:
LinkList * m_next;
data_t m_data;
public:
LinkList(data_t data){
m_data = data;
m_next = NULL;
}
virtual ~LinkList(){
if(m_next != NULL){
delete m_next;
}
}
void InsertData(data_t data){
LinkList * p = this;
while(p->m_next != NULL) p = p->m_next;
p->m_next = new LinkList(data);
}
void DeleteData(data_t data){
LinkList * f = NULL, * p = this;
while(p->m_data != data){
if(p->m_next != NULL){
f = p;
p = p->m_next;
}else{
return;
}
}
if(p != NULL){
if(p == this){
p->m_data = 0; // Only Clear
}else{
f->m_next = p->m_next;
p->m_next = NULL;
delete p;
}
}
}
void PrintList(){
LinkList * p = this;
while(p != NULL){
cout << p->m_data << endl;
p = p->m_next;
}
}
};
测试程序:
#include <iostream.h>
typedef double data_t;
#include "LinkList.hpp"
int main(int argc, char* argv[])
{
printf("Hello World!\n");
LinkList lsList(4);
lsList.InsertData(4);
lsList.InsertData(67);
lsList.InsertData(43);
lsList.InsertData(3);
lsList.DeleteData(67);
lsList.PrintList();
fflush(stdin); getchar();
return 0;
}
private:
LinkList * m_next;
data_t m_data;
public:
LinkList(data_t data){
m_data = data;
m_next = NULL;
}
virtual ~LinkList(){
if(m_next != NULL){
delete m_next;
}
}
void InsertData(data_t data){
LinkList * p = this;
while(p->m_next != NULL) p = p->m_next;
p->m_next = new LinkList(data);
}
void DeleteData(data_t data){
LinkList * f = NULL, * p = this;
while(p->m_data != data){
if(p->m_next != NULL){
f = p;
p = p->m_next;
}else{
return;
}
}
if(p != NULL){
if(p == this){
p->m_data = 0; // Only Clear
}else{
f->m_next = p->m_next;
p->m_next = NULL;
delete p;
}
}
}
void PrintList(){
LinkList * p = this;
while(p != NULL){
cout << p->m_data << endl;
p = p->m_next;
}
}
};
测试程序:
#include <iostream.h>
typedef double data_t;
#include "LinkList.hpp"
int main(int argc, char* argv[])
{
printf("Hello World!\n");
LinkList lsList(4);
lsList.InsertData(4);
lsList.InsertData(67);
lsList.InsertData(43);
lsList.InsertData(3);
lsList.DeleteData(67);
lsList.PrintList();
fflush(stdin); getchar();
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询