[英]Remove first node from a linked list and return it without allocating or deallocating memory.(C programming)
我不允許釋放內存或分配新內存(列表已經為我分配了)。 所以本質上我正在嘗試編寫一個函數,例如,
struct node* returnAndRemoveFirstNode(struct node* head)
{
struct node* returned = head;
struct node* temp = head->next;
returned->next = NULL;
head = temp;
return returned;
}
這不起作用,因為當我設置返回-> 旁邊為空時,我還將頭的旁邊設置為空。 我不確定如何解決這個問題,我確定有很多方法可以解決它,只是不確定如何解決。 對於 (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;
};
我相信你沒有正確理解原始任務。
然而,從列表中刪除第一個節點並返回它的函數可以如下所示
struct node * returnAndRemoveFirstNode( struct node **head )
{
struct node *returned = *head;
if ( *head != NULL )
{
*head = ( *head )-next;
returned->next = NULL;
}
return returned;
}
請注意,通常列表可以為空。 所以指向頭節點的指針可以等於NULL。
如果要遵循評論中的描述
最初的任務是從包含特定數據的列表中刪除所有節點,並將所有這些節點添加到不同的列表中並返回它。
那么該函數可以如下所示,如下面的演示程序所示。
#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
struct node* returnFirstNode(struct node** head)
{
struct node* returned = *head;
struct node* next = (*head)->next;
*head = next;
returned->next = NULL;
return returned;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.