#include
#include
using namespace std;
class Node
{
public:
int num;
Node* next;
Node(int n)
{
num = n;
next = NULL;
}
};
class List
{
Node* head;
Node* tail;
int nodecount;
public:
List()
{
nodecount = 0;
tail = head = NULL;
}
void Insert(int n)
{
Node* tmp = new Node(n);
if (nodecount == 0)
{
head = tail = tmp;
nodecount++;
return;
}
if (tmp->num < head->num)
{
tmp->next = head;
head = tmp;
nodecount++;
return;
}
if (tmp->num > tail->num)
{
tail->next = tmp;
tail = tmp;
nodecount++;
return;
}
Node* cur = head;
while (cur != NULL)
{
if (tmp->num > cur->num && tmp->num < cur->next->num)
{
tmp->next = cur->next;
cur->next = tmp;
nodecount++;
return;
}
cur = cur->next;
}
}
void print()
{
Node* cur = head;
for (int i = 1; i < nodecount; i++)
{
cout << cur->num << ' ';
cur = cur->next;
}
cout << cur->num;
}
};
bool delta(int n)
{
if (n <= 1)
return false;
else if (n == 2)
return true;
else
{
for (int i = 2; i < sqrt(n); i++)
{
if (n % i == 0)
{
return false;
}
}
}
return true;
}
int main()
{
List list;
while (1)
{
int shu;
cin >> shu;
if (delta(shu))
{
list.Insert(shu);
}
else
{
list.print();
return 0;
}
}
}
while (cur != NULL)
{
if (tmp->num > cur->num && tmp->num < cur->next->num)
===========
以上代码的cur->next存在风险,比如已有节点为3和5,这时候又输入一个5,代码就会崩掉。因为之前两个小于head和大于tail的代码都不成立。
建议将小于head和大于tail改为小于等于head和大于等于tail