MST

星途 面试题库

面试题:C语言指针的指针在链表结构中的应用

假设有一个双向链表结构,节点定义为struct Node { int data; struct Node *prev; struct Node *next; }; 请编写一个函数,使用指针的指针来实现向链表头部插入新节点的操作,并简要说明指针的指针在这个场景中的作用。
22.1万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *prev;
    struct Node *next;
};

// 向链表头部插入新节点的函数
void insertAtHead(struct Node **head, int newData) {
    struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
    newNode->data = newData;
    newNode->prev = NULL;
    newNode->next = *head;
    if (*head != NULL) {
        (*head)->prev = newNode;
    }
    *head = newNode;
}

// 打印链表的函数
void printList(struct Node *head) {
    struct Node *current = head;
    while (current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
    printf("\n");
}

int main() {
    struct Node *head = NULL;
    insertAtHead(&head, 10);
    insertAtHead(&head, 20);
    insertAtHead(&head, 30);
    printList(head);
    return 0;
}

指针的指针在这个场景中的作用:

  1. 能够修改头指针:函数参数如果是普通指针struct Node *head,在函数内部对head的修改只是修改了这个局部指针变量,不会影响到函数外部真正的头指针。而使用指针的指针struct Node **head,通过解引用*head,就可以修改函数外部真正的头指针,使得新插入的节点成为链表新的头部。

  2. 灵活性:这种方式使得函数更加通用,可以处理不同链表的头指针,而不需要在函数内部硬编码头指针的名称或使用全局变量。