我或多或少只是在学习C,我得到了一个简单的任务,处理双链表、动态数据分配和递归。我创建了一个只有10个整数的数组,并试图使用递归将这些整数放入一个排序的双链表中。我在将节点插入链表时遇到了一些问题;我想我已经放下了第一个节点,但我不确定其余的节点是否有意义。现在我也有一个分割错误。。。谢谢你的帮助!
#include <stdio.h>
#include <stdlib.h>
#define N 10
typedef struct node_ {
int value;
struct node_ *next;
struct node_ *prev;
} node;
void insert(node **head, node *cur, node *p);
void print_list(node *cur);
void print_list(node *cur)
{
if (!cur) {
printf("n");
return;
} else {
printf("%d ", cur->value);
print_list(cur->next);
}
}
int main(int argc, char *argv[])
{
int i;
int data[N] = {2, 7, 3, 9, 4, 4, 0, 8, 7, 100};
node *p, *head;
head = NULL;
for (i = 0; i < N; i++) {
p = (node *)malloc(sizeof(node));
p->value = data[i];
insert(&head, head, p);
}
print_list(head);
}
void insert(node **head, node *cur, node *p)
{
if(*head == NULL)
{
p->next = (*head);
//(*head)->prev = p;
(*head) = p;
}
if(p->value < cur->value)
{
cur->prev->next = p;
p->prev = cur->prev;
cur->prev = p;
p->next = cur;
}
insert(head, cur, p);
//p->next = *head;
//*head = p;
}
递归insert
函数中有一些错误。这将在我的代码的评论中很清楚:
void insert(node **head, node *cur, node *p)
{
if(*head == NULL) // the list will contain a single element
{
p->next = p->prev = NULL;
*head = p;
return; // we're done for this case!
}
if(p->value < cur->value)
{
p->prev = cur->prev;
p->next = cur;
cur->prev = p;
if(cur->prev != NULL) // what if cur is the head? there is no cur->prev!
cur->prev->next = p;
else
*head = p; // p becomes the new head
return; // we're done!
}
if(cur->next == NULL) // if cur is the last in the list, we just insert p after it
{
cur->next = p;
p->next = NULL;
p->prev = cur;
}
else // now we can proceed recursively and check the next element
insert(head, cur->next, p);
}
我认为是函数insert
本身必须分配新节点。
它应该有两个参数:指向头的指针和要添加的值。
这里有一个演示程序,展示了如何在中编写函数
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct node
{
int value;
struct node *next;
struct node *prev;
} node;
void insert( node **current, int value )
{
if ( *current == NULL || value < ( *current )->value )
{
node *tmp = malloc( sizeof( node ) );
tmp->value = value;
tmp->next = *current;
if ( *current != NULL )
{
tmp->prev = ( *current )->prev;
( *current )->prev = tmp;
}
else
{
tmp->prev = NULL;
}
*current = tmp;
}
else if ( ( *current )->next == NULL )
{
node *tmp = malloc( sizeof( node ) );
tmp->value = value;
tmp->next = ( *current )->next;
tmp->prev = *current;
( *current )->next = tmp;
}
else
{
insert( &( *current )->next, value );
}
}
void print_list( node *current )
{
if ( current == NULL )
{
printf( "n" ) ;
}
else
{
printf( "%d ", current->value );
print_list( current->next );
}
}
#define N 10
int main( void )
{
node *head = NULL;
srand( ( unsigned int )time( NULL ) );
for ( int i = 0; i < N; i++ )
{
int value = rand() % N;
printf( "%d ", value );
insert( &head, value );
}
printf( "n" );
print_list( head );
return 0;
}
程序输出可能看起来像
4 9 0 0 6 7 2 7 3 3
0 0 2 3 3 4 6 7 7 9
当然,您还需要编写一个递归函数,为节点释放所有已分配的内存。