gpt4 book ai didi

c - C 中的多重赋值?

转载 作者:太空狗 更新时间:2023-10-29 16:00:27 25 4
gpt4 key购买 nike

我在 C 中遇到过一个代码,其中似乎有对指针的多重赋值(在 block 引号中)。这是如何运作的? 'prev' 甚至没有定义。

代码如下:

// A complete working C program to demonstrate deletion in singly
// linked list
#include <stdio.h>
#include <stdlib.h>

// A linked list node
struct Node
{
int data;
struct Node *next;
};

/* Given a reference (pointer to pointer) to the head of a list
and an int, inserts a new node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}

/* Given a reference (pointer to pointer) to the head of a list
and a key, deletes the first occurrence of key in linked list */
void deleteNode(struct Node **head_ref, int key)
{
// Store head node
struct Node* temp = *head_ref, *prev;

// If head node itself holds the key to be deleted
if (temp != NULL && temp->data == key)
{
*head_ref = temp->next; // Changed head
free(temp); // free old head
return;
}

// Search for the key to be deleted, keep track of the
// previous node as we need to change 'prev->next'
while (temp != NULL && temp->data != key)
{
prev = temp;
temp = temp->next;
}

// If key was not present in linked list
if (temp == NULL) return;

// Unlink the node from linked list
prev->next = temp->next;

free(temp); // Free memory
}

// This function prints contents of linked list starting from
// the given node
void printList(struct Node *node)
{
while (node != NULL)
{
printf(" %d ", node->data);
node = node->next;
}
}

/* Drier program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;

push(&head, 7);
push(&head, 1);
push(&head, 3);
push(&head, 2);

puts("Created Linked List: ");
printList(head);
deleteNode(&head, 1);
puts("\nLinked List after Deletion of 1: ");
printList(head);
return 0;
}

最佳答案

定义

struct Node* temp = *head_ref, *prev;

相同
struct Node* temp = *head_ref;
struct Node *prev;

这是一些非常基本的语法,即使是非常糟糕的教程或书籍也应该展示。

关于c - C 中的多重赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51617926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com