【发布时间】:2017-02-28 06:36:06
【问题描述】:
我正在制作一个排序的链表,用户输入一个数字并将数字插入到排序位置。我目前在使用排序功能时遇到问题。
class Node
{
public:
int data;
class Node *next;
Node(int info, Node *ptr = 0)
{
data = info;
next = ptr;
}
};
class Node *head = NULL;
class stack
{
private:
Node *temp;
public:
stack()
{
temp = 0;
}
bool isEmpty()
{
return temp == NULL;
}
我决定使用插入函数(它称为排序,但实际上它只是将一个节点插入到链表中),这就是为什么我有一个当前指针和一个前一个指针。我想我的问题是我走在正确的道路上吗?我是新手,所以我只需要一点指导来解决这个问题。任何提示将不胜感激。
void sort(int data)
{
class Node *born = new Node(data);
Node* current = head;
Node* previous = NULL;
//the list is empty case
if (isEmpty())
temp = born;
else
{
while (current != NULL)
{
if (current->data >= temp->data)
{
born->next = current;
temp = born;
break;
}
else
{
previous = current;
current = temp->next;
}
}
if (current == head)
{
born->next = head;
head = born;
}
else
{
born->next = current;
previous->next = born;
}
/*else
{
born->next = temp;
temp = born;
}*/
}
}
void print()
{
cout<<"stack from the top"<<endl;
for(Node *top = temp; top != 0; top=top->next)
cout << top->data << " ";
cout << endl;
/*while(temp != NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
*/
}
int pop()
{
if (isEmpty())
return -999;
int intReturn = temp->data;
Node *top;
top = temp;
temp = temp->next;
delete top;
return intReturn;
}
};
int main(void)
{
int num=0;
stack boss;
while(num!=-1)
{
cout<<"Please Enter a Number"<<endl;
cin >> num;
if (num == -1)
boss.print();
else
boss.sort(num);
}
cout<<endl<<endl;
system("PAUSE");
return 0;
}
【问题讨论】:
-
在这里快速浏览一下。
current = temp->next;有问题,因为此时可能没有设置 temp。那行应该是current = current->next;。 -
如果你想要一个链表数据结构,只需使用std::list 或std::forward_list。如果您想对
std::list进行排序,请使用std::sort 或std::stable_sort。 -
归并排序适用于链表。记住不要复制或移动元素,而是拼接列表。
-
你的
class Node *head = NULL;的作用是什么?
标签: c++ sorting linked-list