【问题标题】:C++ Pointer-based LinkedListC++ 基于指针的链表
【发布时间】:2018-02-17 21:34:35
【问题描述】:

我开始学习 C++ - 特别是指针。我想我会尝试一个基本的链表。这是我的代码:

#include <iostream>

using namespace std;

struct Linked {
    Linked *next;
    string val;
};

Linked newLinked(string val);
Linked addLinked(Linked l, string val);
void printLinked(Linked l);

Linked newLinked(string val) {
    Linked l;
    l.val = val;
    l.next = NULL;
    return l;
}

Linked addLinked(Linked l, string val) {
    Linked n = newLinked(val);
    n.next = &l;
    return n;
}

void printLinked(Linked l) {
    Linked *r = &l;
    while (r != NULL) {
        cout << (*r).val << endl;
        r = (*r).next;
    }
}

int main() {
    Linked list = newLinked("This is the root node.");
    list = addLinked(list, "This is the second node.");
    list = addLinked(list, "This is the third node.");
    list = addLinked(list, "This is the fourth, and final, node.");
    printLinked(list);
    return 0;
}

对不起,如果我的格式很糟糕或者我违反了惯例,我还在学习这些。 (如果你愿意,请继续指出我可以如何改进我的代码风格,我来自 Java/JS 背景!)

运行时,我得到这个:

This is the fourth, and final, node.
�;��R�;��R 
This is the fourth, and 
�;��R�;��R 

我的猜测是,包含较早字符串的内存正在被覆盖——“这是第四个,并且”的长度与“这是第二个节点”的长度相同。

不幸的是,我不知道为什么会这样......我希望这里的某人能够指出我(哈哈)正确的方向。

【问题讨论】:

  • addLinked 你写n.next = &amp;l;l 是一个参数,只存在到函数结束然后消失。 n.next 然后将指向垃圾。正确的方向应该是here
  • 不使用值工厂函数newLinked,只需定义类Linked的构造函数即可。
  • -> 表示法等同于“(*).”,所以你可以(并且应该)用 r->val 代替 (*r).val
  • 你的所有函数都应该收到并返回Linked*
  • 互联网上有大量的链表示例和教程,您可以与您的版本进行比较。

标签: c++ string pointers


【解决方案1】:

这就是你可以让你的代码工作的方法。

struct Linked {
Linked *next;
string val;
};

Linked* newLinked(string val);
Linked* addLinked(Linked* l, string val);
void printLinked(Linked l);

Linked* newLinked(string val) {
   Linked *l = new Linked;
   l->val = val;
   l->next = NULL;
   return l;
}

Linked* addLinked(Linked* l, string val) {
   Linked *n = newLinked(val);
   n->next = l;
   return n;
}

void printLinked(Linked* l) {
    Linked *r = l;
    while (r != NULL) {
       cout << (*r).val << endl;
       r = (*r).next;
    }
}

int main(){
    Linked *list = newLinked("This is the root node.");
    list = addLinked(list, "This is the second node.");
    list = addLinked(list, "This is the third node.");
    list = addLinked(list, "This is the fourth, and final, node.");
    printLinked(list);

    return 0;
}

请注意,这会导致内存泄漏,就像我们执行 new 但没有 delete 一样。我们需要类似的东西:

void destroyList(Linked *l){
   while(l){
      Linked *r = l->next;
      delete l;
      l = r;
   }
}

避免泄漏。在 main() 的末尾调用这个 destroyList

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 2013-08-07
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 2022-11-21
    • 2012-03-28
    相关资源
    最近更新 更多