【问题标题】:Find first and second element in list C++在 C++ 列表中查找第一个和第二个元素
【发布时间】:2014-10-29 18:44:41
【问题描述】:

这是我在 C++ 中实现列表的程序。我输入元素直到 0。程序正确显示了第一个元素,但第二个元素是错误的。我可能在第二种情况下犯了错误

if (p -> next == first) {
    secondElement = first -> data;
}

。你能说它有什么问题吗。谢谢

#include "stdafx.h"
#include "iostream"
using namespace std;

struct Node {
    int data;
    Node *next;
};

int firstElement;
int secondElement;

int main()
{
    Node *first = 0;
    Node *p;

    cout << "Enter a list" << endl;
    int i;
    while (true) {

        cin >> i;
        if (i == 0) break;


        p = new Node;
        p -> data = i;


        p -> next = first;

        if (first == 0) {
            first = p;
            firstElement = first -> data;
        }

        if (p -> next == first) {
            secondElement = first -> data;
        }       

        first = p;

    }

    cout << "First element is: " << firstElement << endl;
    cout << "Second element is: " << secondElement << endl;
    cout << "List: ";

    p = first;
    while (p) {
        cout << p -> data << " ";
        p = p -> next;
    }
    cout << endl;

    return 0;
}

【问题讨论】:

  • 为什么不直接使用 std::list ?
  • 这是我的任务。我必须手动完成
  • 我相信它打印的第一个和第二个元素相同。
  • 您是否想采取后进先出的行为?
  • 一些通用的cmets:不要使用new/delete,改用std::unique_ptr等智能指针。我看到你已经在回避delete,但这只是意味着你在泄漏。不要将0 用作空指针常量。请改用nullptr。在实际程序中,应该像cin &gt;&gt; i 这样的输入操作成功并且故障得到适当处理。应该首选使用"\n" 而不是endlendl 做了一些通常不需要的额外操作。包括像#include &lt;iostream&gt; 这样的iostream,而不是使用引号。

标签: c++ algorithm list


【解决方案1】:

你可以这样做(我刚刚编辑了你的 while 循环):

while (true) {

    cin >> i;
    if (i == 0) break;


    p = new Node;
    p -> data = i;
    p -> next = 0;

    if (first != 0 && first->next == 0)
        secondElement = p->data;

    p -> next = first;

    if (first == 0) {
        first = p;
        firstElement = first -> data;
    }

    first = p;

}

希望这是你想要实现的......

【讨论】:

    【解决方案2】:

    每次循环时,您都将元素的指针设置为第一个。

    p -> next = first;
    

    然后在检查第二个元素时,您将检查指针是否设置为第一个元素,它总是如此。

     if (p -> next == first) // This is always true
    

    您必须使用一些不同的检查来查看它是否是列表中的第二个条目,例如:

    if (p->next && !p->next->next) // only true second time around
    {
        secondElement = p -> data; // also note the change here
    }
    

    【讨论】:

      【解决方案3】:
      p -> next = first;
      ......
      enter code here
       if (p -> next == first) {  //it's always true here
      

      你应该有

       if (p -> next == 0) {
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-18
        • 1970-01-01
        相关资源
        最近更新 更多