Удалить первый узел из связанного списка и вернуть его без выделения или освобождения памяти. (C программирование) - PullRequest
0 голосов
/ 12 марта 2020

Мне не разрешено освобождать память или выделять новую память (список уже выделен для меня). По сути, я пытаюсь написать такую ​​функцию, как

struct node* returnAndRemoveFirstNode(struct node* head)
{
    struct node* returned = head;
    struct node* temp = head->next;
    returned->next = NULL;
    head = temp;
    return returned;
}

. Это не работает, так как, когда я устанавливаю return-> рядом со значением null, я также устанавливаю head рядом со значением null. Я не уверен, как решить эту проблему, я уверен, что есть много способов решить ее, просто не знаю, как. Для списка в форме (1-> 2-> 3-> 4) исходный список и возвращаемый узел выглядят как (1-> Null)

//Here is the node struct in case you need it
//I am not allowed to alter the struct..
struct node{
int data;
struct node *next;
};

Ответы [ 2 ]

1 голос
/ 12 марта 2020

Я уверен, что вы не правильно понимаете исходную задачу.

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

struct node * returnAndRemoveFirstNode( struct node **head )
{
    struct node *returned = *head;

    if ( *head != NULL ) 
    {
        *head = ( *head )-next;
        returned->next = NULL;
    }

    return returned;
}

Pay Обратите внимание, что в целом список может быть пустым. Таким образом, указатель на головной узел может быть равен NULL.

Если следовать описанию в вашем комментарии

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

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

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

struct node
{
    int data;
    struct node *next;
};

int push_front( struct node **head, int data )
{
    struct node *new_node = malloc( sizeof( struct node ) );
    int success = new_node != NULL;

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

    return success;
}

void output( struct node *head )
{
    for ( ; head != NULL; head = head->next )
    {
        printf( "%d -> ", head->data );
    }

    puts( "null" );
}

struct node * remove_if( struct node **head, int cmp( int data ) )
{
    struct node *new_list = NULL;

    for ( struct node **current = &new_list; *head != NULL; )
    {
        if ( cmp( ( *head )->data ) )
        {
            *current = *head;
            *head = ( *head )->next;
            ( *current )->next = NULL;
            current = &( *current )->next;
        }
        else
        {
            head = &( *head )->next;
        }
    }

    return new_list;
}

int odd( int data )
{
    return data % 2 != 0;
}

int even( int data )
{
    return data % 2 == 0;
}

int main(void) 
{
    const int N = 10;

    struct node *head = NULL;

    for ( int i = N; i != 0; --i ) push_front( &head, i );

    output( head );

    putchar( '\n' );

    struct node *even_head = remove_if( &head, even );

    output( head );
    output( even_head );

    putchar( '\n' );

    struct node *odd_head = remove_if( &head, odd );

    output( head );
    output( odd_head );

    putchar( '\n' );

    return 0;
}

Вывод программы

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> null

1 -> 3 -> 5 -> 7 -> 9 -> null
2 -> 4 -> 6 -> 8 -> 10 -> null

null
1 -> 3 -> 5 -> 7 -> 9 -> null
0 голосов
/ 12 марта 2020
struct node* returnFirstNode(struct node** head)
{
    struct node* returned = *head;
    struct node* next = (*head)->next;
    *head = next;
    returned->next = NULL;
    return returned;
}
...