[英]Insert Function using strcmp()
I'm trying to make an insert function, but I don't know if I'm allowed to used a char string and a node in the argument. 我正在尝试制作插入函数,但不知道是否允许在参数中使用char字符串和节点。
Does this work? 这样行吗? Why not?
为什么不?
void insert(char* str, node* head) {
if (head == NULL) {
node* new_node = malloc(sizeof(struct node));
assert(new_node != NULL);
new_node->value = strdup(str);
}
while (head != NULL) {
if (strcmp(str, head->value)) {
node *new_node = malloc(sizeof(struc node));
assert(new_node != NULL);
new_node->link = head;
new_node->value - strdup(str);
}
}
node *prev = head;
head = head->link;
You havet to return the new head of the list by return value. 您不必按返回值返回列表的新标题。 If you insert one node you have to allocate memory for one node.
如果插入一个节点,则必须为一个节点分配内存。 Don't forget the initialize member
prev
of the first node and the member link
of the last node with NULL
: 不要忘记第一个节点的初始化成员
prev
和最后一个节点的成员link
为NULL
:
node* insert(char* str, node* head)
{
node* new_node = malloc(sizeof(struct node));
assert(new_node != NULL);
new_node->value = strdup(str);
new_node->link = NULL; // successor of new node is NULL
if ( head == NULL )
{
new_node->pev = NULL; // prdecessor of first node is NULL
head = new_node;
return new_node; // head was NULL, return new head
}
node *lastNode = head; // go to last node of list
while ( head->link != NULL )
lastNode = lastNode->link; // step one forward
lastNode->link = new_node; // successor of last node is new node
new_node->prev = lastNode; // predecesor of new node is last node
return head;
}
- --
node *head = NULL;
head = insert( "abc", head );
head = insert( "def", head );
An other solution would be to use an in and output paramter for your paramter head
in function insert
: 另一种解决方案是在函数
insert
为参数head
使用in和output参数:
void insert(char* str, node** head)
// ^^ in and output parameter
{
node* new_node = malloc(sizeof(struct node));
assert(new_node != NULL);
new_node->value = strdup(str);
new_node->link = NULL; // successor of new node is NULL
node* prev = NULL;
node* act = *head;
while ( act != NULL ) // go to last node in list
{
prev = act;
act = act->link; // step one forward
}
new_node->prev = prev; // predecessor of new node is last node or NULL
if ( prev == NULL )
*head = new_node; // new node is the first node in list,
// write the new node back to head
else
prev->link = new_node; // successor of last node is new node
}
- --
node *head = NULL;
insert( "abc", &head );
insert( "def", &head );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.