多型實現通用連結串列
阿新 • • 發佈:2020-12-22
連結串列節點的資料域型別不再為具體的資料型別,而是通過一個基類指標引入,達到不借助模板而是通過多型實現通用連結串列
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
class Object
{
public:
Object(){}
virtual ~Object(){}
virtual void Print()const = 0;
virtual bool Compare(Object *pObj) = 0;
};
class List;
class ListNode
{
friend class List;
public:
ListNode()
{
data = NULL;
next = NULL;
}
ListNode(Object *pObj)
{
data = pObj;
next = NULL;
}
~ListNode()
{
delete data;
data = NULL;
}
private:
Object *data;
ListNode *next;
};
class List
{
public:
List()
{
head = last = new ListNode;
}
bool PushBack(Object *pObj)
{
ListNode *s = new ListNode(pObj);
if (s == NULL)
return false;
last->next = s;
last = s;
return true;
}
void Print()const
{
ListNode *p = head->next;
while (p != NULL)
{
p->data->Print();
p = p- >next;
}
cout << ".Nul" << endl;
}
void InsertOrder(Object* pObj)
{
ListNode *s = new ListNode(pObj);
ListNode *q = head;
ListNode *p = head->next; // q-->p
while (p != NULL && p->data->Compare(s->data))
{
q = p;
p = p->next;
}
s->next = p;
q->next = s;
if (p == NULL)
last = s;
}
~List()
{
ListNode *p = head->next;
while (p != NULL)
{
head->next = p ->next;
delete p;
p = head->next;
}
delete head;
head = last = NULL;
}
private:
ListNode *head;
ListNode *last;
};
class IntObject : public Object
{
public:
IntObject(int d = 0):data(d){}
~IntObject(){}
void Print()const
{
cout << data << "-->";
}
bool Compare(Object *pObj)
{
IntObject *pInt = dynamic_cast<IntObject*>(pObj);
if (pInt != NULL)
{
return data < pInt->data;
}
return false;
}
private:
int data;
};
class StrObject :public Object
{
public:
StrObject(const char* str)
{
if (str == NULL)
{
data = new char[1];
data[0] = '\0';
}
else
{
data = new char[strlen(str) + 1];
strcpy(data, str);
}
}
void Print()const
{
cout << "\"" << data << "\"" << "-->";
}
bool Compare(Object *pObj)
{
StrObject *pStr = dynamic_cast<StrObject*>(pObj);
if (pStr != NULL)
{
return strcmp(data, pStr->data) < 0;
}
return false;
}
StrObject()
{
delete[] data;
data = NULL;
}
private:
char *data;
};
int main()
{
List intList;
List strList;
for (int i = 0; i <= 10; i++)
{
IntObject *pInt = new IntObject(i);
intList.PushBack(pInt);
}
intList.Print();
const char *str[] = {"hello", "c++", "you", "are", "simple" };
for (int i = 0; i < 5; i++)
{
StrObject *pStr = new StrObject(str[i]);
strList.PushBack(pStr);
}
strList.Print();
List orderList;
const char *str1[] = { "hello", "c++", "you", "are", "simple" };
for (int i = 0; i < 5; i++)
{
StrObject *pStr = new StrObject(str1[i]);
orderList.InsertOrder(pStr);
}
orderList.Print();
system("pause");
return 0;
}