>假设你有一个链表,你想制作不同的副本并向这个列表添加一些元素,但你不知道这个数字。每个链表必须具有不同的地址才能更改。链表:
struct path {
int node;
struct path *next;
};
每次我将链表的起始地址发送到带有值的函数时,该函数都会在另一个地址中复制链表,并将值添加到列表的末尾(多次(。
我在代码中实现了以下内容,以在链表上创建和添加新元素:
/* Head and Tail for Linked Lists */
struct path *pathHead = NULL;
struct path *pathTail = NULL;
void newPathElement(int node) {
struct path *rv = malloc(sizeof (struct path));
rv->node = node;
if (pathHead == NULL) {
pathHead = rv;
pathHead -> next = NULL;
pathTail = pathHead;
} else {
pathTail -> next = rv;
pathTail = rv;
pathTail -> next = NULL;
}
}
注意 我想制作链表的不同副本。每个副本都有其头部和尾部,每个副本列表的头部和尾部都不同。
函数签名是以下签名:
struct path *copyPath(struct path *head, struct path *tail, int node){
}
我们初学者应该互相帮助:)
事实上,编写一个将新节点附加到列表的函数或将其代码合并到复制列表的函数就足够了。
给你。
#include <stdio.h>
#include <stdlib.h>
struct path
{
int node;
struct path *next;
};
int append( struct path **head, int node )
{
struct path *tmp = malloc( sizeof( struct path ) );
int success = tmp != NULL;
if ( success )
{
tmp->node = node;
tmp->next = NULL;
while ( *head ) head = &( *head )->next;
*head = tmp;
}
return success;
}
struct path * copy( const struct path *source )
{
struct path *destination = NULL;
for ( ; source; source = source->next ) append( &destination, source->node );
return destination;
}
void display( const struct path *head )
{
for ( ; head; head = head->next )
{
printf( "%d ", head->node );
}
}
int main(void)
{
struct path *first_list = NULL;
const int N = 10;
for ( int i = 0; i < N; i++ ) append( &first_list, i );
display( first_list );
putchar( 'n' );
struct path *second_list = copy( first_list );
display( second_list );
putchar( 'n' );
return 0;
}
程序输出为
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
您可以通过以下方式使函数copy
更高效
struct path * copy( const struct path *source )
{
struct path *destination = NULL;
for ( struct path **tmp = &destination; source; source = source->next )
{
append( tmp, source->node );
tmp = &( *tmp )->next;
}
return destination;
}