在使用密钥 ZZZ 时,尝试将新节点移动到前面时遇到问题。它最终删除了以前的头部。我正在寻找的输出是:
第一个输入: 第二个输入: 新遍历:第三个输入: 新遍历: ABC ABC DEF DEF DEF DEF -> ZZZ 键用于 ABC ABC GHI GHI -> DEF 密钥用于 ABC
Destination *insertAfter ( Destination *head, Destination *node, char *key )
{
struct Destination *roam = head;
if (head == NULL)
{
printf( "IF HEAD = NULLn");
head = node;
return head;
}
else
{
char zzz[4] = { 'Z','Z','Z',' ' };
while ( ( ( *roam ).next ) == NULL)
{
if ( strcmp( zzz, key) == 0 )
{
printf( "KEY CHECKED OUTn" );
( *roam ).next = roam;
head = node;
return head;
}
else if ( !strcmp( zzz, key) )
{
printf( " 1st ELSE IF LOOPn" );
( *node ).next = head;
head = node;
return head;
}
else if ( !strcmp( ( ( *roam ).code ), key) )
{
printf( "2nd ELSE IF LOOP n" );
struct Destination* temp = NULL;
if ( ( ( *roam ).next) != NULL)
{
temp = ( *roam ).next;
( *roam ).next = node;
( *node ).next = temp;
}
else
{
printf("inside the 2nd ELSE IF LOOPn" );
( *roam ).next = node;
}
return head;
}
// roam = ( *roam ).next;
}
// printf("OUT OF WHILE LOOPn" );
// ( *roam ).next = node;
//
// return head;
}
}
这个问题在不同的网站上已经回答了无数次,因为它是一个如此普遍的问题。请访问此链接并向下滚动。您将看到将元素添加到链表头部的过程如下:
typedef struct node {
int val;
struct node * next;
} node_t;
...
void push(node_t ** head, int val) {
node_t * new_node;
new_node = malloc(sizeof(node_t));
new_node->val = val;
new_node->next = *head;
*head = new_node;
}
然后,您可以根据所描述的条件调用推送函数。