【发布时间】:2018-06-19 16:22:20
【问题描述】:
我刚开始学习数据结构,一直在尝试用 C 逐步实现一个简单的单链表。我一直在关注一个在线教程,在展示如何将节点插入到列表的开头时,它在函数参数中使用了双星号,我无法理解,并且教程没有详细解释。
然后我解决了这个问题并在没有双指针的情况下实现了函数(通过使用临时节点),但我很想了解和了解我看到的实现是如何工作的以及我自己是如何实现的。
我最近自学了指针,所以我不能说我对它们感到满意。实际上,这就是我开始学习数据结构并进行更多练习的原因之一。我通常了解 取消引用 指针的工作原理,但在这种情况下,我不确定它在函数头中的使用方式和用途。
如果您能解释以下函数的工作方式,我将不胜感激。
这是我不太明白的功能。 (source)
void push(node_t ** head, int val) {
node_t * new_node;
new_node = malloc(sizeof(node_t));
new_node->val = val;
new_node->next = *head;
*head = new_node;
}
这是我的实现:
/*
// Singly Linked List Implementation
// 2018/01/10
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node *next;
} node_t;
void addNodeBegin (node_t *head, int val);
void addNodeEnd (node_t *head, int val);
void printLinkedList();
void freeList(struct node* head);
int main(void) {
node_t *head = NULL;
head = malloc(sizeof(node_t));
if (head == NULL) { return 1; }
head->val = 1;
head->next = NULL;
head->next = malloc(sizeof(node_t));
head->next->val = 2;
head->next->next = NULL;
addNodeEnd(head, 5);
addNodeBegin(head, 10);
printLinkedList(head);
freeList(head);
}
// Insert a node to the beginning of the linked list
void addNodeBegin (node_t *head, int val) {
node_t *newNode = NULL;
newNode = malloc(sizeof(node_t));
newNode->val = val;
newNode->next = head->next;
head->next = newNode;
node_t *tmp = NULL;
tmp = malloc(sizeof(node_t));
tmp->val = head->val;
head->val = newNode->val;
head->next->val = tmp->val;
free(tmp);
}
// Insert a node to the end of the linked list
void addNodeEnd (node_t *head, int val) {
node_t *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = malloc(sizeof(node_t));
current->next->val = val;
current->next->next = NULL;
}
// Print the linked list
void printLinkedList(node_t *head) {
node_t *current = head;
while (current != NULL) {
printf("%d\n", current->val);
current = current->next;
}
}
// Remove the list (and free the occupied memory)
void freeList(struct node* head) {
struct node* tmp;
while (head != NULL) {
tmp = head;
head = head->next;
free(tmp);
}
}
【问题讨论】:
-
你基本上要求一个关于指针的教程。 StackOverflow 不是这样的地方。通过您最喜欢的搜索引擎查找教程。选择您个人也以最容易理解的方式编写的一种。解决它。非常重要:拿一张纸和一支笔。将变量的值表示为矩形内的数字/字符串。将指针的值表示为矩形,其中箭头指向其他矩形。尤其是指向指针的指针。扮演计算机并执行程序。
-
在“C”语言中,使用指针至少有两个常见的原因:分配内存时和函数修改参数值时。在
push函数中,你有这两个原因:head指向一些分配的内存,函数修改head值。这就是它使用双指针的原因。
标签: c pointers data-structures singly-linked-list