2013-03-17 57 views
2

我是一个C++初学者,我正在尝试定义一个BubbleSort函数来对链表中的元素进行排序。C++ BubbleSort LinkedList

//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; 
     } 

    } 
    } 
} 

你们能不能帮我解决这个问题: 但在

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.  

这里是核心代码中出现错误? 我用调试,但仍然找不到解决方案。 谢谢。

+0

我认为这是目前'=电流 - > nextPtr'所引发错误。不确定。为什么不在函数的开头检查'firstPtr'是否为'0'? – Shoe 2013-03-17 04:59:22

回答

1

在您的内部循环中,假设您试图查看其数据时current->nextPtr不为空。这不是列表中最后一个节点的情况。尝试从

current != 0

改变你的内循环条件

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