2011-04-27 85 views
1

我想知道確定單鏈表是否爲空的最好和最簡單的方法。檢查單向鏈表是否爲空C++

我需要創建一個布爾方法嗎?

感謝

Read方法

無效列表::閱讀(istream的& R) {

char c[13]; 
r >> c; 
r >> numberOfInts; 

Node *node = new Node(); 

for(int i = 0; i < numberOfInts; i++) 
{ 
    r >> node->data; 
    cout << node->data << endl; 
    node->next = new Node; 
    //node = node->next; 

    head = node; 
} 
} 
else 
{ 
    if(node->data > head->data) 
    { 
     head->next; 
    } 
    else if(node->data < head->data) 
    { 
     Node* tempNode; 
     tempNode = head; 
     head->data = node->data; 
     node->data = tempNode->data; 
    } 
} 
system("pause"); 

}

頭文件

class Node 
{ 
public: 
    Node() {} 
    Node(int d, Node* q = 0) : data(d), next(q) {} //constructor with parameters data and next 
    int data; //holds data in node 
    Node* next;//pointer to next node 
}; 

class List 
{ 
public: 
    void Read(istream&); 
    void Write(ostream&); 

    void setReadSort(bool); 
    void sortOwn(); 
    void insertionSort(Node*); 
    bool isEmpty(); 

    bool _sortRead; 
    int numberOfInts; 

    List(void); 
    ~List(void); 
protected: 
    Node *head; 
    Node current; 
}; 
+0

對不起,如果您需要了解更多信息 – 2011-04-27 16:19:01

+0

「列表」,不應該有一個「當前」數據成員,因爲「當前」節點僅在列表中執行某些操作的情況下才有意義 - 根據定義,它是暫時的,而不是數據模型的一部分。 – 2011-04-27 17:39:43

回答

2

這完全取決於實施。然而,通常這可以通過檢查第一個節點是否存在/具有內容/等來快速完成。

+0

第一個節點總是存在,如果它沒有讀入它,那麼讀入的內容是內存地址-8etc ... – 2011-04-27 16:24:48

+0

@Tazzy:如果第一個節點總是存在,它可能將數據「存儲」在指針中或類似。只需檢查指針是否爲NULL。 – 2011-04-27 16:25:46

+0

不,無指針:( – 2011-04-27 16:30:12

0

是的。原因是:有時我們使用迭代器來插入元素,處理迭代器上元素的數量會非常不舒服(或不可能)。這就是爲什麼許多STL實現具有線性時間的原因,即size_t size(void)函數。 bool empty(void)是檢查列表是否爲空且時間不變的有效方法。

只是要注意:當你使用STL更喜歡使用bool empty(void)size_t size(void)。更多的信息在:Meyers: Effective STL

的功能很簡單:

bool empty(void) const 
{ 
    return (this->begin() == this->end()); 
} 

你的情況:

bool empty(void) const 
{ 
    return (this->head == 0); 
} 
+0

,我認爲,但沒有結束部分 – 2011-04-27 16:44:59

+0

我不需要把== 0 COS沒有說是空的 – 2011-04-27 16:47:23

+0

我總是寫'== 0',因爲它更容易閱讀。當然:你也可以在不使用'== 0'的情況下使用它。 – Naszta 2011-04-27 16:48:56

0

我沒有測試這一點,但它應該工作。

改變程序來說明總是存在的頭部。

[編輯]更改程序佔類,而不是一個結構

bool isEmpty(){return (this->head == NULL)}; 

這會得到更正確的結果

還有一件事,我看到你正在使用的系統(「暫停「);.我知道這是家庭作業,但這是非常糟糕的做法。更好的方法是首先清除stdin中的緩衝區(如果需要),然後忽略一個字符。一個例子是:

cin >> somenumber; // Extract a number (assuming its safe) 
cin.ignore(1, 10); // Ignore 1 character, or a newline, whichever comes first 
        //^this clears the buffer, it does NOT wait for input since 
        // the formatted extraction left a character in the buffer ('\n') 
cin.ignore();  // Essentially the same as above, but since there is nothing in 
        // the buffer, it reads a single character from stdin 
+0

對投票的解釋是適當的。 – 2011-04-27 16:43:54

+0

isEmpty方法明顯地打破了 – 2011-04-27 17:13:28

+0

wasnt我,我還沒有投票,甚至不知道如何投票 – 2011-04-27 17:15:58