简体   繁体   English

main中的链表实现

[英]Linked list implementation in main

I am new to linked lists.My exercises are something like:"write a function which puts the value x to the end of your linked list".So , my code will look like this:(p is a pointer to the first value)我是链表的新手。我的练习类似于:“编写一个函数,将值 x 放到链表的末尾”。所以,我的代码将如下所示:(p 是指向第一个值的指针)

struct node
{
    int info;
    node *next;
};

void LastElement(int x , node * & p)
{
    node *q = new node;
    q = p;
    while (q -> next != NULL)
        q = q -> next;
    
    q->next->info = x;
    q->next->next = NULL;
}

My question is:How do i verify this program?What do i write in the main function?Will i create an array or...?我的问题是:我如何验证这个程序?我在主函数中写了什么?我会创建一个数组还是...?

You should write a test function that validates that the linked list is of the correct shape.您应该编写一个测试函数来验证链表的形状是否正确。 That test function could, for example, walk your linked list in parallel with a std::vector and test that elements are the same pairwise and that the length is the same.例如,该测试函数可以与std::vector并行遍历您的链表,并测试元素是否成对相同且长度相同。 Its prototype would be something like bool testEqual(node * list, std::vector<int>)它的原型类似于bool testEqual(node * list, std::vector<int>)

Now simply call LastElement a few times and then check that the resulting linked list is of the correct shape.现在只需调用LastElement几次,然后检查结果链表的形状是否正确。

Here is a reference implementation, you can adapt it to arrays if you want:这是一个参考实现,如果需要,您可以将其调整为数组:

bool testEqual(node * list, const std::vector<int>& test) {
   for (int i = 0; i < test.size() && list != nullptr; i++)
      if (test[i] != list->info) {
          std::cerr << "mismatch at index " << i << std::endl;
          return false;
      }
      list = list->next;
   }
   if (i == test.size() && list == nullptr) {
      return true;
   } else {
      std::cerr << "list is too " << (list == nullptr ? "short" : "long" ) << std::endl;
      return false;
   }
}

Simply call this as testEqual(theList, {1,2,3,4,5}) .只需将其称为testEqual(theList, {1,2,3,4,5})

To simply test your code you can do a function like:要简单地测试您的代码,您可以执行以下功能:

void check(node *p) {
    while (p != nullptr) {
        std::cout << p->info << std::endl;
    }
}

But this function doesn't gonna work with your actual code, because when you do:但是此函数不适用于您的实际代码,因为当您这样做时:

q->next->info = x;
q->next->next = NULL;

Your programme gonna crash, because q->next at this moment is null.你的程序会崩溃,因为此时q->next为空。 If you wan't to add a new node whit the value x create a new one and put it in like:如果您不想添加值x的新节点,请创建一个新节点并将其放入:

// generate the need node
node *new_node = new node;
new_node->info = x;
// push the new node to the linked list
node->next = new_node;

But if you wan't to modify the last node do:但是,如果您不想修改最后一个节点,请执行以下操作:

node->info = x;
// but not like you did:
// node->next->info = x;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM