c - 如何使用双指针插入单向链表?

标签 c linked-list

codepad link enter image description here我正在尝试使用双指针插入到链表中。但我不明白我哪里出错了我跟进了堆栈溢出的其他链接,我什至提到了几本书所以请帮助我。我保留了代码用于在位置 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;
  }

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

最佳答案

您的打印功能不正确。您正在 (*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");
  }

您将收到以下输出:

the elements are.. 5
the elements are.. 4 5

关于c - 如何使用双指针插入单向链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22111854/

相关文章:

php - PHP在32位和64位架构上的区别?

c - 我自己的sqrt()函数哪里出错了?

c - 实现一个函数以递归方式返回有效的获胜条件 - C

c - C 编程中的链表

c - "expected expression"goto 标签错误(非本地 goto)

c - 如何将函数作为参数放入 C 中?

c - 为什么我的 C 队列中出现段错误(核心已转储)?

c++ - 指向指针 : partitioning a linked list 的指针

c++ - 合并 K 排序列表中大小 2 列表的错误

c - 如何在链表中存储路由