1

我试图弄清楚确定单链表是否为空的最佳和最简单的方法是什么。

我需要创建一个布尔方法吗?

谢谢

读取方法

无效列表::读取(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;
};
4

3 回答 3

2

这完全取决于实现。但是,这通常可以通过检查第一个节点是否存在/是否有内容/等来非常快速地完成。

于 2011-04-27T16:19:32.323 回答
0

是的。原因是:有时我们使用迭代器插入元素,处理迭代器上的元素数量会很不舒服(或不可能)。这就是为什么许多 STL 实现对size_t size(void)函数具有线性时间的原因。bool empty(void)是检查列表是否为空且具有恒定时间的有效方法。

请注意:当您使用 STL 时,更喜欢使用bool empty(void)反对size_t size(void). 更多信息见:迈耶斯:有效的 STL

功能很简单:

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

在你的情况下:

bool empty( void ) const
{
  return ( this->head == 0 );
}
于 2011-04-27T16:20:16.713 回答
0

我没有对此进行测试,但它应该可以工作。

[编辑] 更改程序以说明始终存在的头部。

[编辑] 更改程序以说明类,而不是结构

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

这将给出更合适的结果

还有一件事,我看到您正在使用 system("pause");。我知道这是家庭作业,但这是非常糟糕的做法。更好的方法是首先清除标准输入中的缓冲区(如果需要),然后忽略一个字符。一个例子是:

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
于 2011-04-27T16:33:29.927 回答