【问题标题】:How to Insert at beginning of Singly Linked List [closed]如何在单链表的开头插入 [关闭]
【发布时间】:2019-08-21 07:29:26
【问题描述】:

我试图在列表的开头插入节点,但无法插入,我认为插入的逻辑似乎是正确的

void display(Node *t)
{
    Node *p = t;
    while (p != 0)
    {
        cout << p->data << ",";
        p = p->next;
    }
}
void Insert(Node *t,int pos,int x)
{
    Node *temp=NULL;
    if(pos==0)
    {
       temp=new Node;
       temp->data=x;
       temp->next=t;
       t=temp;
    }
}
int main()
{
     Node *p = new Node;
     Node *q = new Node;

     p->data = 4;
     p->next = q;

     q->data=6;
     q->next=NULL;

     Insert(p,0,89);
     Insert(p,0,80);

     display(p);
}

我希望输出 80,89,4,6,

但我得到的实际输出是 4,6,

【问题讨论】:

  • Node 在哪里定义?请提供minimal reproducible example
  • Insert(t,0,89);t 是什么?
  • “但我得到的实际输出是 4,6”,不。请确保您发布的代码确实符合您的要求
  • 您的详细信息有误,但您在发布的代码中省略了详细信息。细节很重要,请发布完整代码。
  • 了解指针最重要的一点是,指针没有什么特别之处。分配给Node* 与分配给int 没有区别。

标签: c++ singly-linked-list


【解决方案1】:

你需要通过引用来传递指针:

void Insert(Node* &t, int pos, int x)

【讨论】:

  • 您不必需要这样做。事实上,最好改写为t = Insert(t,0,89);
  • @john 不加解释的“更好”是不加解释的“你需要”的小弟 ;)
  • @foreknownas_463035818 说得好,我修改了我的评论(稍微)
  • @foreknownas_463035818 有时:P
  • @john 也因为返回类型为 void。
猜你喜欢
  • 1970-01-01
  • 2018-04-05
  • 2010-12-31
  • 2016-07-02
  • 2021-01-18
  • 1970-01-01
  • 2021-09-08
  • 1970-01-01
相关资源
最近更新 更多