【发布时间】:2020-04-21 17:15:00
【问题描述】:
我有一个问题,需要使用函数将单链表拆分为 2 部分:Split(n1, n2) 其中 n1 = 元素的位置,n2 是要拆分的元素数。我设法想出了一个算法和一个测试程序:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct Node
{
int value;
struct Node *next;
};
int push_front( struct Node **head, int value )
{
struct Node *new_node = malloc( sizeof( struct Node ) );
int success = new_node != NULL;
if ( success )
{
new_node->value = value;
new_node->next = *head;
*head = new_node;
}
return success;
}
void display( const struct Node *head )
{
for ( ; head != NULL; head = head->next )
{
printf( "%d -> ", head->value );
}
//puts( "null" );
}
struct ListPair
{
struct Node *head1;
struct Node *head2;
};
struct ListPair split( struct Node **head, size_t pos, size_t n )
{
struct ListPair p = { .head1 = NULL, .head2 = NULL };
struct Node **current1 = &p.head1;
struct Node **current2 = &p.head2;
for ( size_t i = 0; *head != NULL && i != pos; i++ )
{
*current2 = *head;
*head = ( *head )->next;
( *current2 )->next = NULL;
current2 = &( *current2 )->next;
}
while ( *head != NULL && n-- )
{
*current1 = *head;
*head = ( *head )->next;
( *current1 )->next = NULL;
current1 = &( *current1 )->next;
}
while ( *head != NULL )
{
*current2 = *head;
*head = ( *head )->next;
( *current2 )->next = NULL;
current2 = &( *current2 )->next;
}
return p;
}
int main(void)
{
const size_t N = 15;
struct Node *head = NULL;
srand( ( unsigned int )time( NULL ) );
for ( size_t i = 0; i < N; i++ )
{
push_front( &head, rand() % N );
}
display( head );
putchar( '\n' );
struct ListPair p = split( &head, 6, 3 );
display( head );
display( p.head1 );
display( p.head2 );
return 0;
}
结果是:
12 -> 14 -> 3 -> 0 -> 12 -> 5 -> 4 -> 0 -> 2 -> 14 -> 1 -> 0 -> 6 -> 0 -> 5 -> null
null
5 -> 4 -> 0 -> 2 -> 14 -> null
12 -> 14 -> 3 -> 0 -> 12 -> 1 -> 0 -> 6 -> 0 -> 5 -> null
但不知道如何将上述实现到我的链表中,即:
typedef struct address_t
{
char name[30];
char storage[5];
char screen[5];
int price;
} address;
typedef address elementtype;
typedef struct node node;
typedef struct node{
elementtype element;
node *next;
};
node *root, *cur, *prev;
请帮忙:(
【问题讨论】:
-
您展示了我为某个问题提供的代码,问题是什么> 使用 malloc 创建节点后,用所需值填充其数据成员。
-
我认为首先你必须编写自己的代码。之后,如果您有任何问题,请提出问题。
标签: c singly-linked-list