对于本声明中的初学者
temp = (list*)malloc(sizeof(list*));
^^^^^
分配的内存大小等于指针的大小,而不是节点的大小。你必须写任何一个
temp = (list*)malloc(sizeof(list));
或
temp = (list*)malloc(sizeof( *temp));
这个 if 语句
if (a->next == NULL)
可以调用未定义的行为,因为最初列表可以为空。所以指针a 可以等于NULL。那就是使用空指针来访问内存。
if-else 语句的 if 和 else 部分之后的这两个代码块没有区别
if (a->next == NULL)//insert to the first node
{
temp->data = b;
temp->next = a;
a = temp;
}
else
{
temp->data = b;
temp->next = a;
a = temp;//
}
这两个代码都是sn-p尝试在列表的开头插入一个新节点。
在单向单向列表的开头插入新节点是一种通用方法。将一个节点附加到这样一个列表的末尾是低效的,因为必须遍历整个列表。
如果你想将一个节点附加到一个单链表的末尾,那么让它成为双面的。
这是一个演示程序。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
} Node;
typedef struct List
{
Node *head;
Node *tail;
} List;
int push_front( List *list, int data )
{
Node *new_node = malloc( sizeof( Node ) );
int success = new_node != NULL;
if ( success )
{
new_node->data = data;
new_node->next = list->head;
list->head = new_node;
if ( list->tail == NULL ) list->tail = list->head;
}
return success;
}
int push_back( List *list, int data )
{
Node *new_node = malloc( sizeof( Node ) );
int success = new_node != NULL;
if ( success )
{
new_node->data = data;
new_node->next = NULL;
if ( list->tail == NULL )
{
list->head = list->tail = new_node;
}
else
{
list->tail = list->tail->next = new_node;
}
}
return success;
}
void output( const List *list )
{
for ( const Node *current = list->head; current != NULL; current = current->next )
{
printf( "%d -> ", current->data );
}
puts( "null" );
}
int main(void)
{
List list = { .head = NULL, .tail = NULL };
const int N = 10;
for ( int i = 0; i < N; i++ )
{
if ( i % 2 != 0 )
{
push_front( &list, i );
}
else
{
push_back( &list, i );
}
output( &list );
}
return 0;
}
它的输出是
0 -> null
1 -> 0 -> null
1 -> 0 -> 2 -> null
3 -> 1 -> 0 -> 2 -> null
3 -> 1 -> 0 -> 2 -> 4 -> null
5 -> 3 -> 1 -> 0 -> 2 -> 4 -> null
5 -> 3 -> 1 -> 0 -> 2 -> 4 -> 6 -> null
7 -> 5 -> 3 -> 1 -> 0 -> 2 -> 4 -> 6 -> null
7 -> 5 -> 3 -> 1 -> 0 -> 2 -> 4 -> 6 -> 8 -> null
9 -> 7 -> 5 -> 3 -> 1 -> 0 -> 2 -> 4 -> 6 -> 8 -> null
在这个演示程序中,使用函数push_back 将偶数插入到列表的末尾,使用函数push_front 将奇数插入到列表的开头。
如果你的 C 编译器不支持指定的初始化器,那么这个声明
List list = { .head = NULL, .tail = NULL };
可以通过以下方式更改
List list = { NULL, NULL };