【问题标题】:Two methods of Traversing nodes and inserting at middle in linked lists链表中遍历节点和中间插入的两种方法
【发布时间】:2015-10-24 07:36:52
【问题描述】:
    void insert()
{   
    struct node *temp;
    struct node*pre=start,*count=start;
    int ps,i,c=0;
    printf("Enter the position where u want to insert\n");
    scanf("%d",&ps);
    if(ps==1)
        {insertbeg();}
    else
    {
     while(count!=0)
    {c++;
    count=count->link;}
            if(ps>c)
            {insertend(ps);}
                        else
                            {
                            temp=(struct node *)malloc(sizeof(struct node));
                                if (temp==NULL)
                                {printf("Memory is full\n");}
                                else
                                {
                                for(i=1;i<ps;i++) //place1
                                {pre=pre->link;}  
                                temp->link=pre;//place2
                                pre=temp;//place3
                                printf("Enter the element to inserted\n");
                                scanf("%d",&temp->data);
                                }
                            }
    }
}

代码运行,但每当我在中间位置插入任何元素时,它都不会使用显示功能显示,而在开头插入 (insertbeg()) 并在结尾插入 (insertend() ) 正常工作和显示。 当我在 1,2&3 的地方替换下面的行时,元素会正常显示。

for(i=1;i<ps-1;i++) 
temp->link=pre->link; 
pre->link=temp;

我想知道为什么会发生这种情况,因为这两组语句看起来是相同的。

【问题讨论】:

  • 无明显调试,DCV。

标签: c insert linked-list


【解决方案1】:

Place3 是最大的不同。当你写pre=temp时,只修改了局部变量pre,而不是前一个节点到下一个节点的链接。这就是为什么您的链表没有显示新元素的原因。

【讨论】:

  • 因为 temp 是一个指针 pre=temp 应该做的是将 temp 的地址存储在指针变量 pre 中(前一个节点链接到下一个节点)然后将数据存储在 temp->data 中,这是相同的作为 pre->data(因为它们是指向相同地址的指针)
  • 有时使用指针可能有点棘手。请记住,每个变量和结构的字段都存储在内存中的唯一地址。前一个节点到下一个节点的链接存储在与pre 不同的地址。即使它们在 place3 之前具有相同的值(它们都指向同一个旧节点),更改 pre 的值只会使 pre 指向其他地方,但不会更改结构的字段 next 的位置以前的节点点。
猜你喜欢
  • 2019-11-08
  • 1970-01-01
  • 1970-01-01
  • 2016-03-30
  • 1970-01-01
  • 2012-10-27
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
相关资源
最近更新 更多