已知一个有序链表类LinkSortList及main函数的部分代码如下,请完成LinkSortList类的成员函数,得到对应的运行结果,勿改动main函数。 //有序表类 template <class T> class LinkSortList { public: LinkSortList( ); //建立只有头结点的空链表 ~LinkSortList(); //析构函数 void Insert(T x); //在有序单链表中插入元素x使序列仍有序 int Length(); //求表长 int DeleteOdd(); //在单链表中删除所有奇数,返回值为奇数个数 void DispList( ); //遍历有序单链表,按序号依次输出各元素 private: Node<T> *first; //单链表的头指针 }; int main( ){ LinkSortList<int> sa; int x; while(1) { cin>>x; if(!x)break; sa.Insert(x); } sa.DispList(); int count=sa.DeleteOdd(); cout<<"Count of deleted odds:"<<count<<endl; sa.DispList(); return 0; }
时间: 2023-05-28 15:07:52 浏览: 159
已知一个有序链表类LinkSortList及main函数的部分代码如下,请完成LinkSortList类的成员函数,得到对应的运行结果,勿改动main函数。
```
#include <iostream>
using namespace std;
//定义结点类
template <class T>
class Node {
public:
T data;
Node<T> *next;
Node(T d, Node<T> *n = NULL) :data(d), next(n) {}
};
//有序表类
template <class T>
class LinkSortList {
public:
LinkSortList() :first(NULL) {} //建立只有头结点的空链表
~LinkSortList(); //析构函数
void Insert(T x); //在有序单链表中插入元素x使序列仍有序
int Length();
int DeleteOdd(); //在单链表中删除所有奇数,返回值为奇数个数
void DispList(); //遍历有序单链表,按序号依次输出各元素
private:
Node<T> *first; //单链表的头指针
};
template<class T>
LinkSortList<T>::~LinkSortList()
{
Node<T> *p;
while (first != NULL)
{
p = first;
first = first->next;
delete p;
}
}
template<class T>
void LinkSortList<T>::Insert(T x)
{
Node<T> *p = first, *q = NULL;
while (p != NULL && x >= p->data)
{
q = p;
p = p->next;
}
Node<T> *newNode = new Node<T>(x);
if (q == NULL)
{
first = newNode;
}
else
{
q->next = newNode;
}
newNode->next = p;
}
template<class T>
int LinkSortList<T>::Length()
{
int count = 0;
Node<T> *p = first;
while (p != NULL)
{
count++;
p = p->next;
}
return count;
}
template<class T>
int LinkSortList<T>::DeleteOdd()
{
int count = 0;
Node<T> *p = first, *q = NULL;
while (p != NULL)
{
if (p->data % 2 == 1)
{
count++;
if (q == NULL)
{
first = p->next;
delete p;
p = first;
}
else
{
q->next = p->next;
delete p;
p = q->next;
}
}
else
{
q = p;
p = p->next;
}
}
return count;
}
template<class T>
void LinkSortList<T>::DispList()
{
Node<T> *p = first;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main()
{
LinkSortList<int> sa;
int x;
while (1)
{
cin >> x;
if (!x)
break;
sa.Insert(x);
}
sa.DispList();
int count = sa.DeleteOdd();
cout << "Count of deleted odds:" << count << endl;
sa.DispList();
return 0;
}
```
阅读全文