【问题标题】:how to insert into the singly linked list using double pointers?如何使用双指针插入单链表?
【发布时间】:2014-03-01 08:05:55
【问题描述】:

codepad link我正在尝试使用双指针插入链接列表。但我不明白我哪里出错了我跟进堆栈溢出的其他链接,我什至提到了几个书籍,所以请帮助我。我将插入代码保留在位置 1。在输出中,之前的插入丢失了。

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

 void insert(node **head,int k,int pos)//k refers to the element to be inserted
{
   if(pos==1)
   {
    node *newnode=(node *)malloc(sizeof(node));
    newnode->data=k;
    newnode->next=*head;
    *head=newnode;
   }
 }

   void print(node **head)
  {
    printf("the elements are.. ");
    while(*head!=NULL)
    {
      printf("%d ",(*head)->data);
     (*head)=(*head)->next;
    }
   printf("\n");
  }
   int main()
   {
        insert(&head,5,1);
        print(&head);
        insert(&head,4,1);
        print(&head);
      return 0;
  }

抱歉缩进不佳。我是初学者,请帮助我。

【问题讨论】:

  • 这不是有效的 C 代码。请通过复制和粘贴的方式发布您正在编译和运行的实际代码。另外,告诉我们它在什么方面不起作用
  • 也许这解释了你在寻找什么:macs.hw.ac.uk/~rjp/Coursewww/Cwww/linklist.html
  • 为什么不将其放入 codepad.org 或类似网站?
  • insert 函数中的 if 在这种情况下是多余的。您正在丢弃 head 的先前值
  • size_t 是无符号类型,所以只能使用非负数。如果您使用size_t pos 代替int pos 并将诸如-842 之类的数字作为位置传递给insert 函数,则会显示警告。如果使用size_t 时没有得到提示,那将是其他人的错。

标签: c linked-list


【解决方案1】:

您的打印功能不正确。你在(*head)=(*head)->next; 中抹去你的头。将函数改为

void print(node **head)
  {
    printf("the elements are.. ");
    node *temp = *head;
    while(temp!=NULL)
    {
      printf("%d ",temp->data);
     temp=temp->next;
    }
   printf("\n");
  }

您将收到以下输出:

元素是.. 5
元素是.. 4 5

【讨论】:

  • 你能解释一下为什么头部没有转到下一个位置
  • 它去了。但是新的值被分配给了头。因此,当您第二次拨打print(&head); 时,您会收到不正确的结果。
  • 所以我正在修改实际指针,非常感谢您发现错误
  • 您可以在第一个和第二个print(&head); 之后添加cout<<head<<endl; 以检查您的head。它不应该改变!。
  • 下次我会这样做
【解决方案2】:

看看这个。

struct node //Missed struct's name
{
    int data;
    node *next;
};

void insert(node **head,int k,int pos)//k refers to the element to be inserted
{
    if(pos==1)
    {
        node *newnode= new node();
        newnode->data=k;
        newnode->next=*head; //You called head which is not a member of node's struct
        *head=newnode;
    }
}

int main()
{
    node *head=NULL;
    insert(&head,5,1);
    insert(&head,4,1);
}

【讨论】:

  • *head 我正在传递函数,在 C++ 中我们可以省略 struct word 对吗?如果我错了,请纠正我
  • 不,我们不能。 & 你不能在 C++ 中这样做: - 调用结构的成员 "head" 没有实例 - 未命名的结构:结构{ .... } - 结构后面没有分号 -*head = 新闻,其中新闻没有在任何地方定义你做得好的是:-传递一个指向列表头的指针,而不是头本身:你传递了 Node* 头而不是 Node* 头。
  • 我认为我们可以在查看此链接后进行编译codepad.org/NyUITHU3
  • 我检查了,它是正确的在旧代码中,当我将节点的成员名称更改为 next 时,您定义了 struct 的成员“head”并调用了 newnode->next(不存在),head (不存在)
  • 哦,对不起,这是我的错误
猜你喜欢
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-22
相关资源
最近更新 更多