改进以下代码#include<iostream> #include<string.h> #include<stdio.h> using namespace std; //链表类的前向声明 template<class T> class list; template<class T> //声明模板 class node { //定义结构模板0-[-[ T val; //val取任意类型,即模板参数类型 node<T>* next; //此处node为结构模板 public: node(){ next = NULL; } node(T a) { val = a; next = NULL; } friend class list<T>; }; //请完成链表类的设计 template<class T> class list { public: list(){} void insert(T t) { if(pFirst==NULL) { pFirst=new node(t); pTail=pFirst; } else { node<T> *p=new node(t); pTail->next=p; pTail=p; } } void print() { for(node<T> *p=pFirst;p;p=p->next) cout<<p->val; } private: static node<T> pFirst; static node<T> pTail; }; template <class T> node<T> list<T>::pFirst=NULL; template <class T> node<T> list<T>::pTail=NULL; int main() { int kind = 0; // 0:表示整型,1:单精度浮点数, 2:字符串 int cnt = 0; cin >> kind >> cnt; //整数链表 if (kind == 0) { list<int> intlist; int nTemp = 0; for (int i = 0; i < cnt; i++) { cin >> nTemp; intlist.insert(nTemp); } intlist.print(); } //浮点数链表 else if (kind == 1){ list<float> floatlist; float fTemp = 0; cout.setf(ios::fixed); cout.precision(1); for (int i = 0; i < cnt; i++) { cin >> fTemp; floatlist.insert(fTemp); } floatlist.print(); } //字符串链表 else if (kind == 2){ list<string> charlist; char temp[100] ; for (int i = 0; i < cnt; i++){ cin >> temp; charlist.insert(temp); } charlist.print(); } else cout << "error"; return 0; }
时间: 2024-01-02 12:04:18 浏览: 72
以下是改进后的代码:
```
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
template<class T>
class Node {
public:
T val;
Node<T>* next;
Node() {
next = NULL;
}
Node(T a) {
val = a;
next = NULL;
}
friend class List<T>;
};
template<class T>
class List {
private:
Node<T>* pFirst;
Node<T>* pTail;
public:
List() {
pFirst = NULL;
pTail = NULL;
}
void insert(T t) {
Node<T>* p = new Node<T>(t);
if (pFirst == NULL) {
pFirst = p;
pTail = pFirst;
}
else {
pTail->next = p;
pTail = p;
}
}
void print() {
for (Node<T>* p = pFirst; p != NULL; p = p->next) {
cout << p->val << " ";
}
}
};
int main() {
int kind = 0; // 0:表示整型,1:单精度浮点数, 2:字符串
int cnt = 0;
cin >> kind >> cnt;
//整数链表
if (kind == 0) {
List<int> intList;
int nTemp = 0;
for (int i = 0; i < cnt; i++) {
cin >> nTemp;
intList.insert(nTemp);
}
intList.print();
}
//浮点数链表
else if (kind == 1) {
List<float> floatList;
float fTemp = 0;
cout.setf(ios::fixed);
cout.precision(1);
for (int i = 0; i < cnt; i++) {
cin >> fTemp;
floatList.insert(fTemp);
}
floatList.print();
}
//字符串链表
else if (kind == 2) {
List<string> stringList;
string temp;
for (int i = 0; i < cnt; i++) {
cin >> temp;
stringList.insert(temp);
}
stringList.print();
}
else
cout << "error";
return 0;
}
```
改进说明:
1. 将链表节点的定义和链表的定义分开,使代码更加清晰易懂;
2. 在链表类中增加私有成员变量pFirst和pTail,用于指向链表的头和尾;
3. 在链表类的构造函数中初始化pFirst和pTail为NULL;
4. 修改了链表的insert方法,使其可以正确处理插入第一个节点的情况;
5. 修改了链表的print方法,使其可以正确处理链表为空的情况;
6. 修改了字符串链表的输入方式,使用string类型代替char数组类型,更加方便易用。
阅读全文