我一直对我的代码错误感到困惑。我创建了一个链表并使用 push()
添加元素并使用 printList()
输出元素,下面的代码工作正常。
#include <stdio.h>
#include <stdlib.h>
struct linkedList {
int _Value;
struct linkedList * _Next;
};
typedef struct linkedList linkedList_t;
/* Function to push a node */
void push( linkedList_t** listHead, int new_data )
{
/* allocate node */
linkedList_t* new_node =
(linkedList_t *) malloc( sizeof(linkedList_t) );
/* put in the data */
new_node->_Value = new_data;
/* link the old list off the new node */
new_node->_Next = *listHead;
/* move the head to point to the new node */
*listHead = new_node;
}
/* Function to print linked list */
void printList( linkedList_t *head )
{
linkedList_t *tmp = head;
while ( tmp != NULL )
{
printf( "%d ", tmp->_Value );
tmp = tmp->_Next;
}
}
int main( int argc, char* argv[] )
{
linkedList_t *head = NULL;
push( &head, 20 );
push( &head, 4 );
push( &head, 15 );
push( &head, 85 );
printList( head );
return 0;
}
问题是,当我将参数更改为单指针时,例如:
void push( linkedList_t* listHead, int new_data )
{
/* allocate node */
linkedList_t* new_node =
(linkedList_t *) malloc( sizeof(linkedList_t) );
/* put in the data */
new_node->_Value = new_data;
/* link the old list off the new node */
new_node->_Next = listHead;
/* move the head to point to the new node */
listHead = new_node;
}
当我调用 printList()
函数时,没有任何反应,我认为这是因为 head
一直等于 NULL
但我不能找出我的代码有什么问题,假设当我在 main 函数
和我的 中调用
如下:push()
时 head
将被更改主要功能
int main( int argc, char* argv[])
{
linkedList_t *head = NULL;
push( head, 20 );
push( head, 4 );
push( head, 15 );
push( head, 85 );
printList( head );
return 0;
}
我需要一些建议。有人帮忙吗?谢谢!
最佳答案
当你使用单指针时,你实际上传递的是头指针的拷贝。在双指针的情况下,您传递的是头指针的地址,以便对其进行更改。
您可以通过微小的更改使代码与单指针版本一起工作。在这种情况下,您需要从推送函数返回头指针。
linkedList_t* push( linkedList_t* listHead, int new_data );
在那种情况下,反射(reflect)的变化将是:-
linkedList_t *head = NULL;
head = push( head, 20 );
head = push( head, 4 );
希望我已经足够清楚了...
关于c++ - 作为双指针 (**) 和单指针 (*) 传递的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26880602/