그래서 이것은 연결 목록 프로그램에 대한 제 코드입니다. 나는 그렇게 위대하지 않다는 것을 알고 있지만 작동한다. ins() 함수를 변경하여 새 요소가 크기에 따라 목록에 삽입되도록합니다. 즉, 목록의 마지막 노드는 가장 큰 정수를 포함하고 가장 작은 것은 첫 번째입니다. 정수는 텍스트 파일에서 읽어 들이며, main()에서 볼 수 있듯이 텍스트 파일의 INSERT 및 REMOVE 명령은 목록에 삽입 (다음 줄의 다음 정수) 명령으로 해석되거나 목록에서 요소를 제거하십시오. 기존 코드로 어떻게 할 수 있습니까? 내 ins() 함수를 수정하려고했지만 목록이 올바르게 정렬되지 않았습니다.이 링크 된 목록에 노드를 삽입하는 가장 좋은 방법은 무엇입니까?
ins()
기능에
#include <stdio.h>
#include <stdlib.h>
struct node {
int number;
struct node *next;
};
/* prototypes */
void ins(struct node *llist, int number);
void rem(struct node *llist);
void sho(struct node *llist);
int main(void)
{
int number;
char command[6];
struct node *llist;
struct node *root;
llist = (struct node *)malloc(sizeof(struct node));
llist->number = 0;
llist->next = NULL;
root = llist;
printf("addr: \n\n%p,%p\n\n", &llist, &root);
FILE *file;
file = fopen("a3data.txt", "r");
if (file == NULL)
{
printf("\n----------------------------------------\n");
printf("| Error. Did not read file. Exiting. |\n");
printf("----------------------------------------\n\n");
exit(1);
}
else
{
while ((fscanf(file, "%s", command)) != EOF)
{
if((strcmp(command, "INSERT"))==0)
{
fscanf(file, "%d", &number);
printf("\nINSERT ", number);
ins(llist, number);
sho(llist);
}
else if((strcmp(command, "REMOVE"))==0)
{
printf("\n REMOVE ");
rem(llist);
sho(llist);
}
}
}
printf("\n");
free(llist);
return(0);
}
void ins(struct node *llist, int number)
{
while(llist->next != NULL)
{
llist = llist->next;
}
llist->next = (struct node *)malloc(sizeof(struct node));
llist->next->number = number;
llist->next->next = NULL;
}
void rem(struct node *llist)
{
while(llist->next->next != NULL)
{
llist = llist->next;
}
llist->next = NULL;
}
void sho(struct node *llist)
{
while(llist->next != NULL)
{
printf("%d ", llist->number);
llist = llist->next;
}
printf("%d", llist->number);
}
그래서 당신은 정렬 된 순서로 노드를 삽입해야합니다 귀하의 경우 기능을 수정? hmm –
제대로 작동합니까, 나는'struct node * llist'가'struct node ** llist'이어야한다고 생각합니다. 그렇지 않으면 호출시 효과가 없습니다 –
['void sortedInsert (struct node ** head_ref, struct node * new_node)'] (http://www.geeksforgeeks.org/given-a-linked-list-which-is-sorted-how-will-you-insert-in-sorted-way/) –