链表中遍历节点和中间插入的两种方法 void insert() { 结构节点*temp; 结构节点*pre=start,*count=start; int-ps,i,c=0; printf(“输入要插入的位置\n”); scanf(“%d”、&ps); 如果(ps==1) {insertbeg();} 其他的 { while(计数!=0) {c++; 计数=计数->链接;} 如果(ps>c) {insertend(ps);} 其他的 { temp=(结构节点*)malloc(sizeof(结构节点)); if(temp==NULL) {printf(“内存已满\n”);} 其他的 { 对于(i=1;ilink;} temp->link=pre;//place2 pre=temp;//place3 printf(“输入要插入的元素\n”); scanf(“%d”,&temp->data); } } } }
代码运行,但每当我在中间位置插入任何元素时,它都不会使用display函数显示,而在开始插入(insertbeg())和结束插入(insertend())都正常工作和显示。 当我替换位置1、2和3中的以下行时,元素将正常显示链表中遍历节点和中间插入的两种方法 void insert() { 结构节点*temp; 结构节点*pre=start,*count=start; int-ps,i,c=0; printf(“输入要插入的位置\n”); scanf(“%d”、&ps); 如果(ps==1) {insertbeg();} 其他的 { while(计数!=0) {c++; 计数=计数->链接;} 如果(ps>c) {insertend(ps);} 其他的 { temp=(结构节点*)malloc(sizeof(结构节点)); if(temp==NULL) {printf(“内存已满\n”);} 其他的 { 对于(i=1;ilink;} temp->link=pre;//place2 pre=temp;//place3 printf(“输入要插入的元素\n”); scanf(“%d”,&temp->data); } } } },c,insert,linked-list,C,Insert,Linked List,代码运行,但每当我在中间位置插入任何元素时,它都不会使用display函数显示,而在开始插入(insertbeg())和结束插入(insertend())都正常工作和显示。 当我替换位置1、2和3中的以下行时,元素将正常显示 void insert() { struct node *temp; struct node*pre=start,*count=start; int ps,i,c=0; printf("Enter the position wh
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);
}
}
}
}
for(i=1;ilink=pre->link;
预->链接=温度;
我想知道为什么会发生这种情况,因为这两组语句似乎是等价的。Place3是最大的区别。当您编写
pre=temp
时,只修改了局部变量pre
,而没有修改前一个节点到下一个节点的链接。这就是链接列表没有显示新元素的原因。无当前deb由于temp是一个指针,pre=temp应该做的是将temp的地址存储在指针变量pre中(它是前一个节点链接到下一个节点的),然后将数据存储在temp->data中,它与pre->data相同(因为它们是指向相同地址的指针)使用指针有时可能有点棘手。请记住,每个变量和结构的字段都存储在内存中唯一的地址。上一个节点到下一个节点的链接存储在与pre
不同的地址。即使它们在place3之前具有相同的值(它们都指向同一个旧节点),更改pre
的值时,只需将pre
指向其他位置,但不会更改上一个节点的结构字段next
的位置。
for(i=1;i<ps-1;i++)
temp->link=pre->link;
pre->link=temp;