单链表定义
点击查看代码
typedef struct node_s {
int val;
struct node_s* next;
}Node;
头插法
点击查看代码
void add_to_head(Node** list, int val) { //因为要改变头指针指向,需要一个指向头指针地址的指针,即二级指针
Node** head = list;
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->val = val;
newNode->next = NULL;
newNode->next = *head;
*head = newNode;
}
设置带有头指针的单链表
点击查看代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node_s {
int val;
struct node_s* next;
}Node;
void add_to_head(Node** head,int val);
int main() {
Node* list = NULL;
add_to_head(&list, 1);
add_to_head(&list, 2);
add_to_head(&list, 3);
add_to_head(&list, 4);
add_to_head(&list, 5);
for (Node* head = list; head != NULL; head = head->next) {
printf("%d ", head->val);
}
return 0;
}
void add_to_head(Node** list, int val) {
Node** head = list;
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->val = val;
newNode->next = NULL;
newNode->next = *head;
*head = newNode;
}
运行结果