【发布时间】:2020-01-03 18:40:25
【问题描述】:
我的老师给了我一道作业题:-
1) 用户输入链表的大小
2) 用户将在链接中输入要输入的数据 列表。
3) 用户将输入我们必须在其中找到的“特定数据值” 上面创建的原始链接列表。
4) 用户将输入要插入的“新数据值” “特定数据值”。
示例 1:
输入值:
4 //size of linked list
9 77 12 6 //values of linked list
12 //specific value which we have to find
8 //new value to be inserted before.
预期输出:
Linked List : ->9->77->8->12->6
示例 2:
输入值:
4 //size of linked list
9 77 12 6 //values of linked list
10 //specific value which we have to find
8 //new value to be inserted before.
预期输出:
Node not found!
Linked List : ->9->77->12->6
这是我为上述问题编写的以下代码。
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <stdbool.h>
struct node //Linked list structure.
{
int data;
struct node *next;
};
int main()
{
int number; //Variable to take in number of linked list.
scanf("%d", &number);
struct node *head; //creating first linked list manually.
head = malloc(sizeof(struct node));
scanf("%d", &head -> data);
head -> next = NULL;
struct node *temp; //"temp" will help in traversing linked list.
temp = head;
int i; //counter variable for loop.
for(i = 1; i < number; i++)
{
struct node *fnnode;
fnnode = malloc(sizeof(struct node));
scanf("%d", &fnnode -> data); //taking in rest of the values.
fnnode -> next = NULL;
temp -> next = fnnode;
temp = temp -> next;
}
int specific;
scanf("%d", &specific); // inputting the specific value we have to traverse to in linked list and insert the value.
struct node *temp2; //"temp2" will help in traversing linked list.
temp2 = head;
temp = head;
while(temp -> data != specific)
{
temp2 = temp;
temp = temp -> next;
if(temp == NULL) //if "temp" reaches the end of the linked list without finding the value then:
{
printf("Node not found!\n");
temp = head;
printf("Linked List : "); //printing the original linked list.
while(temp != NULL)
{
printf("->%d", temp -> data); //printing the original linked list.
temp = temp -> next;
}
return 0; // TERMINATING the program here by returning value 0.
}
}
//If data is found then code below will execute.
struct node *fnnode;
fnnode = malloc(sizeof(struct node));
scanf("%d", &fnnode -> data); //Taking in the data which needs to be inserted.
temp2 -> next = fnnode;
fnnode -> next = temp;
temp = head;
printf("Linked List : ");//printing the new linked list.
while(temp != NULL)
{
printf("->%d", temp -> data);
temp = temp -> next;
}
temp = NULL;
free(temp);
temp2 = NULL;
free(temp2);
return 0;
}
但是问题是我收到了这个错误:
运行时错误。
我的程序有什么错误?
【问题讨论】:
-
我试过了,确实得到了您预期的输出,没有任何错误。
-
@jmq 即使我得到了正确的输出,但仅适用于已知的测试用例。
-
如果您在第一个元素之前插入,您的代码将不起作用。如:4 / 1 2 3 4/ 1 / 8
-
@jmq 没错,当输入为无限循环时:4 -> 9 12 77 8 -> 9 -> 1
标签: c list undefined-behavior singly-linked-list