C++ BubbleSort LinkedList
C++ BubbleSort LinkedList
我是一个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
相关文章:
- C++:正在检查LinkedList中的回文-递归方法-错误
- 创建LinkedList退出,返回代码为-11(SIGSEGV)
- 在c++中实现LinkedList时,应出现未处理的错误
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 已修改的LinkedList未在文本文件本身中更新
- 如何在 c++ 中处理 LinkedList 的指针
- C++ push() 和 pop() 方法使用指针的动态 LinkedList 的问题
- 在 FreeRTOS 中使用 LinkedList 无法保存值
- 为什么像C++和Java这样的语言有一个内置的LinkedList数据结构
- 将对象添加到LinkedList C 中
- 使用简单的代码从分类的LinkedList中删除重复的节点
- C++中嵌套在另一个 LinkedList 中的 LinkedList 整数上的回调函数问题
- LinkedList实现C 错误指针间接
- 将链接列表复制到linkedlist的引用
- LinkedList removePosition 删除错误的元素
- 在多线程中使用LinkedList队列
- 如何将int数组分配给linkedlist struct
- 具有 LinkedList 的迭代器类
- 基于C 指针的LinkedList
- LinkedList C 中的反向打印