링크 된 목록 (노드)을 작성한 다음 역순으로 프로그램을 작성하고 있습니다. 연결된 목록에는 데이터와 다음 주소가 포함됩니다.C : 링크 된 목록 반전시 문제점
typedef struct node{
int data;
struct node *next;
}node;
먼저 링크드리스트를 만듭니다.
struct node *Insert_value(int dataInput,node* head)
{
node *new_node=NULL;
new_node = malloc(sizeof(node));
new_node -> next = head;
new_node -> data = dataInput;
head = new_node;
return head;
}
그런 다음이 데이터를 인쇄하는 함수를 만듭니다. (나는 PrintNode라고 불렀다.)
while(head!= NULL)
{
printf("%d\t",head->data);
head= head->next;
}
printf("\n");
}
마지막으로 링크 된 목록을 역순으로 만들기위한 함수.
struct node* Reversing(node **head)
{
node *current, *previous, *first;
current = previous = first = *head;
first = first->next->next;
current = current->next;
previous ->next = NULL;
current->next = previous;
while(first != NULL)
{
previous = current;
current = first;
first = first -> next;
previous->next = current;
}
return current;
}
내 전체 프로그램입니다.
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
struct node *Insert_value(int dataInput,node* head);
struct node * Reversing(node **head);
void PrintNode(node *head);
main()
{
node *head = NULL;
int i=0,dataInput;
while(i!=5)
{
printf("input your elements: ");
scanf("%d",&dataInput);
head = Insert_value(dataInput,head);
i++;
}
PrintNode(head);
head = Reversing(&head);
PrintNode(head);
}
struct node *Insert_value(int dataInput,node* head)
{
node *new_node=NULL;
new_node = malloc(sizeof(node));
new_node -> next = head;
new_node -> data = dataInput;
head = new_node;
return head;
}
struct node* Reversing(node **head)
{
node *current, *previous, *first;
current = previous = first = *head;
first = first->next->next;
current = current->next;
previous ->next = NULL;
current->next = previous;
while(first != NULL)
{
previous = current;
current = first;
first = first -> next;
previous->next = current;
}
return current;
}
void PrintNode(node* head)
{
while(head!= NULL)
{
printf("%d\t",head->data);
head= head->next;
}
printf("\n");
}
많은 시간을 디버깅 한 후에 이러한 기능이 정상적으로 작동한다는 것을 알고 있습니다. 그러나 역순 함수 후 head
변수의 다음 노드 주소는 NULL입니다. 설명하고 조언을 해줄 수 있습니까?
'목록을 free'하는 것을 잊지 마세요, 예를 들어, 'while (head! = NULL) {node * victim = head; head = head-> next; 무료 (피해자); }' –