2013-03-17 37 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