//写得很勉强 我是初学者 希望大家多多指教!
//用链表保存数据
//.h文件
#ifndef LIST_H_
#define LIST_H_
#include<string>
using std::string;
typedef string ItemType;
class List
{
public:
List();
~List();
List(const List&aList);
bool isEmpty()const;
int getLength()const;
void remove(int index);
void retrieve(int index,ItemType & dataItem)const;
void enList(ItemType newItem1,ItemType newItem2);
void insert(int index,ItemType newItem1,ItemType newItem2);
void show()const;
private:
typedef struct ListNode
{
ItemType item1;
ItemType item2;
ListNode * next;
}LinkList,*pLinkList;
int size;
ListNode * head;
ListNode * find(int index1);
};
#endif
//.cpp文件
#include<iostream>
#include<cstdlib>
#include"2.h"
List::List():size(0),head(NULL) {}
List::List(const List & aList):size(aList.size)
{
if(aList.head==NULL)
head=NULL;
else
{
head=new LinkList;
head->item1=aList.head->item1;
head->item2=aList.head->item2;
pLinkList newPtr=head;
for(pLinkList origPtr=aList.head->next;
origPtr!=NULL;origPtr=origPtr->next)
{
newPtr->next=new LinkList;
newPtr=newPtr->next;
newPtr->item1=origPtr->item1;
newPtr->item2=origPtr->item2;
}
newPtr->next=NULL;
}
}
List::~List()
{
while(!isEmpty())
remove(1);
}
bool List::isEmpty()const
{
return size==NULL;
}
int List::getLength()const
{
return size;
}
void List::insert(int index,ItemType newItem1,ItemType newItem2)
{
int newLength=getLength()+1;
pLinkList newPtr=new LinkList;
if(newPtr==NULL)
std::cout<<"NO allocate!";
else
{
size=newLength;
newPtr->item1=newItem1;
newPtr->item2=newItem2;
if(index==1)
{
newPtr->next=head;
head=newPtr;
}
else
{
pLinkList prev=find(index-1);
newPtr->next=prev->next;
prev->next=newPtr;
}
}
}
void List::remove(int index)
{
pLinkList cur;
--size;
if(index==1)
{
cur=head;
head=head->next;
}
else
{
pLinkList prev=find(index-1);
cur=prev->next;
prev->next=cur->next;
}
cur->next=NULL;
delete cur;
cur=NULL;
}
void List::show()const
{
pLinkList cur=head;
for(;cur!=NULL;cur=cur->next)
std::cout<<cur->item2<<',';
std::cout<<std::endl;
}
List::pLinkList List::find(int index1)
{
pLinkList cur=head;
for(int i=1;i<index1;i++)
cur=cur->next;
return cur;
}
//main函数
#include"2.h"
#include<iostream>
#include<string>
using std::string;
using namespace std;
int main()
{
List list;
string str1,str2;
int count1=0;
cout<<"请输入翻译的短语个数: ";
cin>>count1;
for(int i=0;i<count1;i++)
{
cout<<"输入两个字符串: ";
cin>>str1;
cin>>str2;
list.insert(1,str1,str2);
}
int count=list.getLength();
cout<<"百度的部门包括"<<count<<"个部门为 ";
list.show();
return 0;
}
链表实现教程
1453

被折叠的 条评论
为什么被折叠?



