面试题答案
一键面试#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;
}
指针的指针在这个场景中的作用:
-
能够修改头指针:函数参数如果是普通指针
struct Node *head
,在函数内部对head
的修改只是修改了这个局部指针变量,不会影响到函数外部真正的头指针。而使用指针的指针struct Node **head
,通过解引用*head
,就可以修改函数外部真正的头指针,使得新插入的节点成为链表新的头部。 -
灵活性:这种方式使得函数更加通用,可以处理不同链表的头指针,而不需要在函数内部硬编码头指针的名称或使用全局变量。