这是一个数据结构作业:
用c++编写如下数据结构:在单向链表的基础上,加入一个自动排序的功能,要求任何时候链表都是升序的。要实现基本的插入和输出功能。
分析:这个链表在功能上类似优先队列 priority_queue 。
相同点:都是非线性结构,都是不限制数据量的容器,每次插入数据后都能保持数据顺序。
不同点:优先队列采用二叉堆结构,实现自动排序的代价很低,而链表则要每次向后遍历,直至找到合适的位置再插入新节点。
当数据多时,每次插入数据都要付出极大代价。
我的代码如下:
需要注意写算法时要留意特殊情况。例如:
1.当链表为空时,数据直接放到头节点。
2.当插入数据比头节点小时,这个数据要取代头节点。
3…
#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;
#define bigint 1e9
struct node{
int data;
node* next;
node(int data){
this->data = data;
this->next = NULL;
}
};
//约定1:链表的数据范围只能在 0 ~ 10^9,否则放弃这个数据。
//约定2:链表的数据又小到大排序
class list{
private:
node* head;
int maxn;
int minn;
int length;
public:
list(){
maxn = -1;
minn = bigint;
length = 0;
}
int Length(){
return length;
}
node* AddNode(int data){
if (data<0 || data>bigint) return NULL;
node* newnode = new node(data);
if (length == 0){
head = newnode;
goto end;
}
if (data <= minn){ //insert before the first node
newnode->next = head;
head = newnode;
goto end;
}
node* temp = head;
node* temp2 = NULL; //the father of temp
while (temp->next != NULL && temp->data <= data){
temp2 = temp;
temp = temp->next;
}
if (temp->next == NULL ){ //insert after the lastest node
temp->next = newnode;
goto end;
}
else{ //inset to the midle of list
temp2->next = newnode;
newnode->next = temp;
}
end:
length++;
minn = min(minn, data);
maxn = max(maxn, data);
return newnode;
}
void Show(){
if (length == 0) {
cout << "The list is empty !\n";
return;
}
cout << "max: " << maxn << " minn: " << minn << endl;
cout << "List: ";
node* temp = head;
while (temp->next != NULL){
cout << temp->data;
temp = temp->next;
cout << " -> ";
}
cout << temp->data << endl;
}
};
//输入0~10e9插入数据 -1输出链表数据 -2查询链表长度 否则结束程序
int main(){
list mylist;
int temp;
while (cin >> temp){
if (temp >= 0 && temp < bigint){
mylist.AddNode(temp);
}
if (temp == -1){
mylist.Show();
}
if (temp == -2){
cout << "the length of list is "<<mylist.Length() << endl;;
}
}
return 0;
}
== 算法不精,如发现错误请指出 2019-3 ==