/*动态数组 使用链表实现*/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
void menu();
template <class T>
class Link_Array
{
typedef struct node
{
T data;
struct node*next;
}Node;
public:
Link_Array()
{
length = 0;
head = NULL;
temp = NULL;
}
void input()//数组中元素的输出
{
Node*pr = head;
cout<<"当前数组中共有"<<length<<"个元素"<<endl;
cout<<"数组中的元素有:";
while(pr != NULL)
{
cout<<pr->data<<"->";
pr = pr->next;
}
cout<<"NULL";
}
void add()//添加元素
{
T num;
Node*pr = NULL;
cout<<"请输入你要添加的元素:";
cin>>num;
pr = new Node;
pr->data = num;
if(head == NULL)head = pr;
else temp->next = pr;
temp = pr;
temp->next = NULL;
length++;
cout<<"元素插入成功!!!"<<endl;
}
void del()//删除元素
{
int position,counter = 0;
Node*pr = head,*p = NULL;
cout<<"请输入元素的位置编号(1-"<<length<<"),以便于做删除操作.";
cin>>position;
if(position < 1 || position > length)cout<<"你输入的位置不存在!!!"<<endl;
else
{
while(counter <= position-1)
{
p = pr;
pr = pr->next;
counter++;
}
p->next = pr->next;
delete pr;
}
cout<<"元素删除成功!!!"<<endl;
}
void change()//按照位置修改元素
{
Node*pr = head;
int position,num,counter = 0;
cout<<"请输入元素的位置编号(1-"<<length<<"),以便于做修改操作.";
cin>>position;
if(position < 1 || position > length)cout<<"你输入的位置不存在!!!"<<endl;
else
{
cout<<"请输入修改后的数字:";
cin>>num;
while(counter < position-1)
{
pr = pr->next;
counter++;
}
pr->data = num;
cout<<"元素修改成功!!!"<<endl;
}
}
void insert()//插入元素
{
Node*pr = head,*p = NULL;
int position,num,counter = 1;
cout<<"请输入元素的位置编号(1-"<<length<<"),以便于做插入操作.";
cin>>position;
cout<<"请输入插入元素的元素值:";
cin>>num;
if(position < 1 || position > length)cout<<"你输入的位置不存在!!!"<<endl;
else
{
p = new Node;
p->data = num;
while(counter < position-1)
{
pr = pr->next;
counter++;
}
p->next = pr->next;
pr->next = p;
cout<<"元素插入成功!!!"<<endl;
}
}
void main1(Link_Array arr)
{
int ch;
menu();
while(1)
{
cout<<"请输入你的选项";
cin>>ch;
if(ch==6)
{
exit(0);
}
else
{
switch (ch)
{
case 1:
arr.add();
break;
case 2:
arr.del();
break;
case 3:
arr.change();
break;
case 4:
arr.insert();
break;
case 5:
arr.input();
break;
}
}
}
}
private:
int length = 0;
struct node*head;
struct node*temp;
};
void menu()
{
cout<<"1. 添加元素 "<<endl;
cout<<"2. 删除元素 "<<endl;
cout<<"3. 修改元素 "<<endl;
cout<<"4. 插入元素 "<<endl;
cout<<"5. 输出元素 "<<endl;
cout<<"6. 退出系统 "<<endl;
}
int main()
{
int x;
Link_Array<int> arr;
Link_Array<char> arr2;
Link_Array<double> arr3;
Link_Array<string> arr4;
printf("请你个用户选择链表元素的类型:
1.整型
2.字符型
3.浮点型
4.字符串");
scanf("%d",&x);
switch(x)
{
case 1:
arr.main1(arr);
break;
case 2:
arr2.main1(arr2);
break;
case 3:
arr3.main1(arr3);
break;
case 4:
arr4.main1(arr4);
break;
}
return 0;
}
将原来的对动态数组的操作改为了对链表的操作,省去了数组空间的扩充,还有减掉了对数组运算符重载的使用,。
使用到了数据结构中的链表,C++中的类模板,大概就是这样吧。
主要的是当我将链表节点的结构体放入类class Link_Array的时候我的类模板T一下子就可以对链表节点中的data数据类型进行改写了,这实在是有点爽哦。
主要还是不知道具体老师让写的题目具体是什么,总之,在多态和虚函数中没有在代码中体现出来,这就有点恼火。
嗨呀,加油吧!!!