我在lubuntu 16.04
中的代码块13.12上获得了此代码程序正在运行,但问题是第一次插入是重复的,即
让我说我先插入整数" 4"到链表。但我得到输出:
4 ,4 ,
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* head = NULL;
void Insert(int c)
{
if(head == NULL) {
struct node* temp = malloc(sizeof(struct node));
temp -> data = c;
temp -> next = NULL;
head = temp;
}
struct node* temp = malloc(sizeof(struct node));
temp -> data = c;
temp -> next = NULL;
struct node* temp1 = head;
while (temp1->next != NULL) {
temp1 = temp1->next;
}
temp1 -> next = temp;
}
void print() {
struct node* temp = head;
printf("list is: \n");
while (temp != NULL) {
printf( "%d ,",temp->data);
temp = temp->next;
}
}
int main () {
printf("How Many Numbers?\n");
int a ,b ,c;
scanf("%d" , &b);
for(a = 0;a<b;a++) {
printf("Enter the numbers \n");
scanf("%d",&c);
Insert(c);
print();
}
return 0;
}
答案 0 :(得分:1)
问题是第一次插入是重复的
<强>原因:强>
if(head==NULL)
以检查插入的节点是否为第一个节点但在此之后您没有提及 else 来限制编译器。< / LI>
head
c
之后创建另一个节点
c=4
的原因,您获得4,4,
作为输出<强>解决方案强>
尝试将insert()
与其他条件一起使用
void Insert(int c)
{
if(head == NULL)
{
struct node* temp = malloc(sizeof(struct node));
temp -> data = c;
temp -> next = NULL;
head = temp;
}
else
{
struct node* temp = malloc(sizeof(struct node));
temp -> data = c;
temp -> next = NULL;
struct node* temp1 = head;
while (temp1->next!= NULL)
temp1 = temp1->next;
temp1 -> next = temp;
}
}
建议:您已经在insert()
函数
struct node* temp = malloc(sizeof(struct node));
temp -> data = c;
temp -> next = NULL;
只需分配temp
一次,然后使用if-else
条件将其插入approprite位置。这也减少了代码行数。这样做:
void Insert(int c)
{
struct node* temp = malloc(sizeof(struct node));
temp -> data = c;
temp -> next = NULL;
if(head == NULL)
{
head = temp;
}
else
{
struct node* temp1 = head;
while (temp1->next!= NULL)
temp1 = temp1->next;
temp1 -> next = temp;
}
}
答案 1 :(得分:0)
这是因为在初始化第一个项目之后Insert
函数“落实”,并再次插入它。在代码块的末尾添加return
。
void Insert(int c)
{
if(head == NULL) {
struct node* temp = malloc(sizeof(struct node));
temp -> data = c;
temp -> next = NULL;
head = temp;
return; //<-- add this line
}
...