C++ BubbleSort LinkedList

C++ BubbleSort LinkedList

本文关键字:LinkedList BubbleSort C++      更新时间:2023-10-16

我是一个c++初学者,我试图定义一个BubbleSort函数来排序链表中的元素。但是在

处出现错误
for(current = firstPtr ; current != 0 ; current= current ->nextPtr)

First-chance exception at 0x01375557 in 111.exe: 0xC0000005: Access violation reading  location 0x00000000.
Unhandled exception at 0x01375557 in 111.exe: 0xC0000005: Access violation reading location 0x00000000.    

核心代码:

 //define Node in class List
 //Node.h
 template<typename T> class List;
template<typename T>
class Node{
friend class List<T>;
public:
Node(T &); //constructor
    T getData() const; //access data
private:
T data;
Node<T> *nextPtr; //point to the next Node
};
template<typename T>
Node<T> ::Node(T &key):data(key),nextPtr(0){}
template<typename T>
T Node<T>::getData()const{
return data;
}

//clase List
//List.h
#include<iostream>
#include"Node.h"
using namespace std;
template <typename T>
class List{
public:
List();
    void insertAtFront(T );
void insertAtBack( T &);
bool removeFromFront(T &);
bool removeFromBack(T &);
bool isEmpty() const;
void print() const;
    void BubbleSort();
private:
Node<T> *firstPtr;
Node<T> *lastPtr;
Node<T> *getNewNode(T&);
};
template<typename T>
List<T> :: List():firstPtr(0),lastPtr(0){}
template<typename T>
void List<T>::BubbleSort(){
Node<T> *current;  //Point to the current node
Node<T> *temp = firstPtr;  //hold the data of first element
    for(bool swap = true; swap;){  // if no swap occurs, list is in order
     swap =false;         
     for(current = firstPtr ; current != 0 ; current= current ->nextPtr){
         if (current->data > current->nextPtr->data){  //swap data
             temp->data = current->data;
             current->data = current->nextPtr->data;
             current->nextPtr->data = temp ->data;
             swap = true;
         }
     }
  }
}

你们能帮我修一下吗?我使用调试,但仍然找不到解决方案。谢谢你。

在您的内部循环中,当您尝试查看其数据时,您假设current->nextPtr不为空。对于列表中的最后一个节点,情况并非如此。尝试从

更改内循环条件

current != 0

current != 0 && current->nextPtr != 0