c - C 中的多重赋值?

标签 c

我在 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/

相关文章:

c - 如何读取文件中用逗号分隔的 2 个浮点值并将其存储到两个数组中,其中每个 float 存储在一个数组中

c - 从文本文件读入结构数组时遇到问题

c++ - 在c中访问越界数组

c - 如何在 C 中 shmget 和 shmat 双数组?

c - 指向空指针的指针 C

c - 释放c中的链表

c - C 中的枚举/类似字典的工具?

C 编程 scanf 帮助

c - 从 C 中的 FIFO 读取 : select() doesn't return?

c - Linux内核的ip_output.c中的简单内存malloc和free