已知一个有序链表类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-27 14:07:16 浏览: 76
//有序表类
template <class T>
class LinkSortList{
public:
LinkSortList( ); //建立只有头结点的空链表
~LinkSortList(); //析构函数
void Insert(T x); //在有序单链表中插入元素x使序列仍有序
int Length(); //求表长
int DeleteOdd(); //在单链表中删除所有奇数,返回值为奇数个数
void DispList( ); //遍历有序单链表,按序号依次输出各元素
private:
Node<T> *first; //单链表的头指针
};
//构造函数
template <class T>
LinkSortList<T>::LinkSortList(){
first = new Node<T>;
first->next = NULL;
}
//析构函数
template <class T>
LinkSortList<T>::~LinkSortList(){
Node<T> *p = first;
while(p != NULL){
Node<T> *q = p;
p = p->next;
delete q;
}
}
//插入元素
template <class T>
void LinkSortList<T>::Insert(T x){
Node<T> *p = first;
while(p->next != NULL && p->next->data < x){
p = p->next;
}
Node<T> *q = new Node<T>;
q->data = x;
q->next = p->next;
p->next = q;
}
//求表长
template <class T>
int LinkSortList<T>::Length(){
Node<T> *p = first->next;
int len = 0;
while(p != NULL){
len++;
p = p->next;
}
return len;
}
//删除奇数
template <class T>
int LinkSortList<T>::DeleteOdd(){
Node<T> *p = first->next;
Node<T> *pre = first;
int count = 0;
while(p != NULL){
if(p->data % 2 == 1){
pre->next = p->next;
delete p;
p = pre->next;
count++;
}else{
pre = p;
p = p->next;
}
}
return count;
}
//遍历并输出
template <class T>
void LinkSortList<T>::DispList(){
Node<T> *p = first->next;
while(p != NULL){
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
阅读全文