#include<stdlib.h>
#include<stdio.h>
struct Node{
int data;
struct Node* next;
};
struct Node* head;
void Insert(int x){
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->next = head;
head = temp;
if(head != NULL)
temp->next = head;
head = temp;
}
void Print(){
struct Node* temp = head;
printf("List is: ");
while(temp != NULL){
printf("%d", temp->data);
temp = temp->next;
}
printf("n");
}
int main(){
head = NULL; //empty list
printf("How many numbers?n");
int n, i;
scanf("%d", &n);
for(int i=0; i < n; i++){
printf("Enter the numbern");
scanf("%d", &x);
Insert(x);
Print();
}
我从编译器得到的错误输出示例:
有多少个数字?
我的输入:2
输入数字:
我的输入:1
列表是:1111111111111111111;在&在上
我甚至没有机会输入第二个数字,因为我把2个数字作为数字的数量。
我重构了代码,它成功了。
无限循环是由于第一个节点指向头部,头部指向第一个节点。
temp->next = head;
head = temp;
因此,当您调用Print()
时,while(temp != NULL)
条件永远不会失败。
#include <stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
};
struct Node* head;
void push_front(int x) {
struct Node *current = malloc( sizeof( struct Node ) );
if (current==NULL) { printf("No available space on heapn"); exit(1); }
current->data = x;
current->next = head;
head = current;
}
void append(int x){
struct Node* temp = malloc(sizeof(struct Node));
if (temp==NULL) { printf("No available space on heapn"); exit(1); }
temp->data = x;
temp->next = NULL;
//check if we have to insert at begining(initial node) or empty list
if (head==NULL){
head=temp;
return ;
}
//traverse till the last node to insert new node
//should not modify the head
struct Node *t=head;
while(t->next != NULL) t=t->next;
t->next= temp;
}
void Print(){
struct Node* temp = head;
printf("List is: ");
while(temp != NULL){
printf("%d->", temp->data);
temp = temp->next;
}
printf("nulln");
}
void destroy_mem(struct Node *head)
{//we need destroy the used memory on heap for further use
struct Node *curr = NULL;
while ((curr = head) != NULL)
{ // set curr to head, stop if list empty.
head = head->next; // moving head to next element.
free(curr); // delete saved pointer.
}
head = NULL;
}
int main(){
head = NULL; //empty list
printf("How many numbers?n");
int n, i,x;
scanf("%d", &n);
for(int i=0; i < n; i++){
printf("Enter the numbern");
scanf("%d", &x);
push_front(x);
}
Print();
destroy_mem(head);
}