簡體   English   中英

通過移動鏈表中的節點進行冒泡排序 (C++)

[英]Bubble Sort By Moving Nodes in Linked List (C++)

我通過比較節點中的值然后移動節點對鏈表進行冒泡排序,但我的函數存在問題。 當我運行我的代碼時,它會很好地創建節點,但是當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");
}

你有很多不好的編碼習慣,比如using namespace std; ,糟糕的命名風格並使用Null而不是nullptr

但是錯誤出在排序片段中。 您正在嘗試交換節點,但如果不使用當前節點之前的節點或使用雙向鏈表,則無法進行交換。 所以在下面的代碼中,我交換了數字而不是節點。

void bubblesort(int size) {
    int i, j, swapped = 1;
    for (i = 0; swapped && i < size; i++){
        swapped = 0;
        Node* temp = head;
        for (j = 0; j < size - i - 1; j++){

            if (temp->number > temp -> next ->number){
                int tempNumber = temp -> number;
                temp -> number = temp -> next -> number;
                temp -> next -> number = tempNumber;
                swapped = 1;
            }
            temp = temp->next;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM