#include<stdio.h>
#include<stdlib.h>
//Linked list implementation
typedef struct SLL{
int info;
struct SLL *link;
}Node;
Node *head=NULL;
// Node *rear=NULL;
void insert_rear(int x)
{
Node *temp=malloc(sizeof(Node));
Node *temp1=NULL;
if(temp==NULL) /* When malloc is unable to fetch Memory */
{
printf("\n Insufficient memory");
}
if(head==NULL) /* When there is no node created */
{
temp->info=x;
temp->link=head;
head=temp;
}
else
temp1=head;
while(temp1->link!=NULL)
{
temp1=temp1->link;
}
printf("\n Temp1=%d",temp1);
temp->info=x;
temp->link=NULL;
temp1->link=temp;
}
void insert_front(int x)
{
Node *temp=malloc(sizeof(Node));
if(temp==NULL) /* When malloc is unable to fetch Memory */
{
printf("\n Insufficient memory");
}
temp->info=x;
temp->link=head;
head=temp;
}
void display()
{
int i=0;
Node *temp=head;
printf("\n List Elements: \n ");
while(temp!=NULL)
{
printf(" %d) %d",++i,temp->info);
temp=temp->link;
printf("\t Link= %u \n",temp);
} printf("\n");
}
void main()
{
int x,choice,i;
printf("\n To insert at front enter 1 \n To insert at rear enter 2 \n To exit enter 4 \n");
while(choice!=4)
{
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter an ELEMENT to be inserted at FRONT \n");
scanf("%d",&x);
insert_front(x);
display();
break;
case 2: printf("Enter an ELEMENT to be inserted at LAST \n");
scanf("%d",&x);
insert_rear(x);
display();
break;
}//End of switch
}//End of while
}//End of main我在编写这个链表程序的时候,发现了一个insert_rear()函数的问题。当我使用insert_front()添加几个元素,然后使用insert_rear()添加后面的元素以及现有节点时,程序工作得很好。但是,当我尝试使用insert_rear()添加一个没有任何现有节点的节点时,由于某种原因,我的程序无法工作。
因此,我花了一些时间修改我的程序,并删除了以下代码部分,以查看是否能够在没有任何现有节点的情况下添加新节点:
else
temp1=head;
while(temp1->link!=NULL)
{
temp1=temp1->link;
}
printf("\n Temp1=%d",temp1);
temp->info=x;
temp->link=NULL;
temp1->link=temp;
}它确实可以工作,也就是说,在拥有任何现有节点之前,只需使用以下代码即可添加到新节点中
if(head==NULL) /* When there are no existing nodes created */
{
temp->info=x;
temp->link=head;
head=temp;
}但是,随着else条件的出现,我的代码无法工作,程序崩溃。请帮我纠正这个错误。我有一种感觉,我做了一些愚蠢的事情,我并不是找不到的。
发布于 2014-09-26 17:54:14
你应该小心使用全局变量,最好完全避免使用它们。在函数insert_front()中,您更改了列表的头部...
约翰尼斯
https://stackoverflow.com/questions/26056571
复制相似问题