【发布时间】:2020-03-29 17:27:47
【问题描述】:
我正在通过比较节点中的值然后移动节点来对链表进行冒泡排序,但我的函数存在问题。当我运行我的代码时,它可以很好地创建节点,但是当 bubblesort() 函数运行时它会抛出一个异常并显示“p2 was nullptr”。我不知道我的代码有什么问题,我们将不胜感激。
这是我的代码:
#include <iostream>
#include <stdlib.h>
using namespace std;
class Node {
public:
int number;
Node* next;
};
class LinkedList {
Node* head;
Node* tail;
public:
LinkedList() {
head = NULL;
tail = NULL;
}
void createnode(int num) {
Node* temp = new Node;
temp->number = num;
temp->next = NULL;
if (head == NULL) {
head = temp;
tail = temp;
}
else {
tail->next = temp;
tail = temp;
}
}
void bubblesort(int size) {
Node* temp;
int i, j, swapped;
for (i = 0; i <= size; i++){
temp = head;
swapped = 0;
for (j = 0; j < size - i - 1; j++){
Node* p1 = temp;
Node* p2 = p1->next;
if (p1->number > p2->number){
Node* temp1 = p2->next;
p2->next = p1;
p1->next = temp1;
temp = p2;
swapped = 1;
}
temp = temp->next;
}
if (swapped == 0)
break;
}
}
void displaynodes() {
Node* temp;
temp = head;
while (temp != NULL) {
cout << temp->number << " ";
temp = temp->next;
}
cout << endl;
}
};
int main() {
LinkedList l;
int size, num;
cout << "How many Numbers Do You Want to Store: ";
cin >> size;
for (int i = 0; i < size; i++) {
cout << "Enter Number " << i+1 << ": ";
cin >> num;
l.createnode(num);
}
system("CLS");
cout << "Data Of Nodes Before Bubble Sort: " << endl;
l.displaynodes();
l.bubblesort(size);
cout << "Data Of Nodes After Bubble Sort: " << endl;
l.displaynodes();
system("pause");
}
【问题讨论】:
-
使用您的调试器逐步完成!那应该是你的第一步。链接列表很棘手,实时监控逻辑的执行对于了解正在发生的事情非常有用。如果你不知道如何使用你的调试器,你在什么环境下工作?
-
@JohnFilleau 好的,我会尝试调试,我正在使用 Visual Studio。
-
如果你不知道如何使用你的调试器,你想在你的问题代码的开头
set a breakpoint,然后通过它single step。实时观察你的变量变化!
标签: c++ singly-linked-list bubble-sort