Как добавить орган в указанное c место в связанном списке в C - PullRequest
0 голосов
/ 25 мая 2020

У меня есть связанный список и два заданных слова. Мне нужно найти индекс первого слова в списке, а затем добавить второе слово сразу после первого слова. На языке C Как это сделать? Спасибо за помощь! это мой код:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 20

typedef struct personNode
{
char name[SIZE];
int age;
struct personNode* next;
}personNode;

 struct personNode* newHead;

personNode* createSong(char name[], int age);
void printList(personNode* head);
void insertAtEnd(personNode** head, personNode* newNode, char friend[]);
void deleteNode(personNode** head, char* name);
void freeList(personNode** head);
void lenght(personNode* p);
void insertAtStart(char name[], int age);
void search(personNode* head, char name[]);
void reverse(personNode** head);

int main(void)
{
personNode* first = NULL;
char name[SIZE] = { 0 };
char friend[SIZE] = { 0 };
int age = 0;
int choice = 0;
int i = 0;
int bigPlace = 0;
printf("\nWelcome to MagshiParty Line Management Software!\n");
do {
    printf("Please enter your choice from the following options:\n1 - Print line\n2 - Add person to line\n3 - Remove person from line\n4 - VIP guest\n5 - Search in line\n6 - Reverse line\n7 - Exit\n");
    scanf("%d", &choice); //ask option from the user
    switch (choice)
    {
        case (1):
            lenght(newHead);
            printList(newHead);
            break;
        case (2):
            getchar();
            printf("Welcome guest!\n");
            printf("Enter name: ");
            fgets(name, SIZE, stdin);
            name[strlen(name) - 1] = '\0';
            printf("Enter age: ");
            scanf("%d", &age);
            getchar();
            printf("Enter names of 3 friends:\n");
            for (i = 0;i <3; i++)
            {
                printf("Friend %d:", i + 1);
                fgets(friend, SIZE, stdin);
                friend[strlen(friend) - 1] = '\0';
            }
            first = createSong(name, age);
            insertAtEnd(&newHead, first, friend);
            break;
        case (3):
            getchar();
            printf("Enter name to remove:\n");
            fgets(name, SIZE, stdin);
            name[strlen(name) - 1] = '\0';
            deleteNode(&newHead, name);
            break;
        case (4):
            getchar();
            printf("VIP GUEST!\n");
            printf("Enter name: ");
            fgets(name, SIZE, stdin);
            name[strlen(name) - 1] = '\0';
            printf("Enter age: ");
            scanf("%d" ,&age);
            insertAtStart(name, age);
            break;
        case (5):
            getchar();
            printf("Enter name to search:\n");
            fgets(name, SIZE, stdin);
            name[strlen(name) - 1] = '\0';
            search(newHead, name);
            break;
        case (6):
            reverse(&newHead);
            printf("Line reversed!\n");
            break;
        case (7):
            printf("GoodBye");
    }
}while(choice!=7);

getchar();
getchar();
return 0;
}


void insertAtEnd(personNode** head, personNode* newNode, char friend[])
{
 personNode* current = head;
while (current != NULL) 
{ 
    if (0 == strcmp(current->name, friend))
    {
        personNode* nxt=current->next; //presently the node which is next to current node
        current->next = newNode;        //now current node will point to new node
        newNode->next=nxt;              // new node will point to the node that was infront of current node
        return;
    }
    current = current->next; 
}
personNode* curr = *head;
if (!*head) // empty list!
{
    *head = newNode;
}
else
{
    while (curr->next) // while the next is NOT NULL (when next is NULL - that is the last node)
    {
        curr = curr->next;
    }

    curr->next = newNode;
    newNode->next = NULL;
}
}

это мой код, у меня больше функций, но они ни к чему. Мне не удалось понять, в чем проблема и почему он не ставит имя в честь друга

Ответы [ 2 ]

0 голосов
/ 25 мая 2020

У меня есть связанный список и два заданных слова. Мне нужно найти индекс первого слова в списке, а затем добавить второе слово сразу после первого слова

Если да, то имя функции insertAtEnd очень сбивает с толку.

Для начала компилятор выдаст ошибку для этого оператора в функции

personNode* current = head;  // Initialize current 

, потому что объявленный указатель имеет тип personNode *, а инициализатор имеет тип personNode ** и неявное преобразование отсутствует. от одного типа указателя к другому ..

void insertAtEnd(personNode** head, personNode* newNode, char friend[])
{
   personNode* current = head;  // Initialize current 
   //... 

Также функция будет иметь неопределенное поведение, если она вызывается для пустого списка.

Функция может выглядеть следующим образом

int insertAtEnd( personNode **head, personNode *newNode, const char *friend )
{
    while ( *head && strcmp( ( *head )->name, friend ) != 0 )
    {
        head = &( *head )->next;
    }

    int success = *head != NULL;

    if ( success )
    {
        newNode->next = ( *head )->next;
        ( *head )->next = newNode;
    }

    return success;
}

Было бы лучше, если бы новый узел был создан внутри функции, а не передавал его в качестве аргумента, потому что, если узел с данной строкой не найден, вы должны освободить его.

Итак, вызов функции может выглядеть, например, как

if ( !insertAtEnd( &head, some_new_node, "friend" ) ) free( some_new_node );

Если узел с данной строкой не найден, возможно, вам следует добавить его в конец списка. В этом случае функция может выглядеть как

void insertAtEnd( personNode **head, personNode *newNode, const char *friend )
{
    while ( *head && strcmp( ( *head )->name, friend ) != 0 )
    {
        head = &( *head )->next;
    }

    if ( *head == NULL )
    {
        *head = newNode;
    }
    else
    {
        newNode->next = ( *head )->next;
        ( *head )->next = newNode;
    }
}
0 голосов
/ 25 мая 2020
    personNode* current = head;
while (current != NULL) 
{ 
    if (0 == strcmp(current->name, friend))
    {
        personNode* nxt=current->next; //presently the node which is next to current node
        current->next = newNode;        //now current node will point to new node
        newNode->next=nxt;              // new node will point to the node that was infront of current node
        return;
    }
    current = current->next; 
}

Приведенный выше код добавит новый узел рядом с узлом, в котором совпадает слово.

...