C语言0基础的前端考研日记:头插法/尾插法创建单链表

一、头插法思路:

1、新节点的下一个节点指向链表的第一个节点

2、将头结点的下一个节点指向新节点

将数据按这个步骤处理后,新节点就会变为链表的第一个节点

前置知识点

malloc 函数 :用于从堆中分配一块指定大小的内存。

内存分配成功返回指向该内存块的指针,否则返回 NULL
使用方法 :('数据类型的指针')malloc('内存大小');
sizeof(Node) 获取Node类型所需内存大小

c 复制代码
#include <stdio.h>
#include <stdlib.h>

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

void insert (Node *L) {
 int x;
 scanf("%d", &x); // 让用户输入数据
 printf("插入%d\n", x); // 控制台打印用户输入的数据
 if (x != 0) { // 当x=0时,插入结束
   Node *n = (Node *)malloc(sizeof(Node)); // 
   printf ("data: %d next: %p\n", n->data, n->next);
   printf ("data: %d next: %p\n", L->data, L->next);
   if (n == NULL) {
     printf("内存分配失败\n");
     exit(0);
   }
   // 将用户输入的数据赋值给新节点
   n->data = x; // L: Head -> FirstNode -> NULL; n: n -> NULL;
   // 让节点n指向节点FirstNode
   n->next = L->next; // L: Head -> FirstNode -> NULL; n: n -> FirstNode -> NULL;
   // 将头结点的next指向新节点
   L->next = n;  // L: Head -> n -> FirstNode -> NULL
   insert(L); // 递归,直到用户输入的数据为0
 };
};
// 打印整个链表
void printList(Node *L) {
   Node *current = L->next; // 从头结点的下一个开始遍历
   while (current != NULL) {
       printf("%d -> ", current->data);
       current = current->next;
   }
   printf("NULL\n"); // 结束标志
}

int main() {
 Node L = {0, NULL};
 insert(&L);
 printList(&L);
 return 0;
}

二、尾插法思路

1、声明变量tail用于存储尾结点的指针,这样可以随时找到链表的尾结点

2、将尾结点的next指向新节点,此时新节点就会成为链表的尾结点

3、将新节点的指针赋值给tail

4、重复以上步骤,直到用户输入的数据为0, 结束链表的创建

相对于头插法只在insert、main做了修改

c 复制代码
void insert (Node *L, Node *last) {
  int x;
  scanf("%d", &x); // 让用户输入数据
  printf("插入%d\n", x); // 控制台打印用户输入的数据
  if (x != 0) { // 当x=0时,插入结束
    Node *n = (Node *)malloc(sizeof(Node));
    // 将用户输入的数据赋值给新节点
    n->data = x; // L: Head -> ... -> lastNode -> NULL; n: n -> NULL;
    // lastNode的next指向新节点
    last->next = n; // L: Head -> ... -> lastNode -> n -> NULL; last: *lastNode;
    // 新节点成为了链表尾结点
    last = n; // last: n;
    insert(L, last); // 递归,直到用户输入的数据为0
  } else {
    last->next = NULL; // 输入结束时将尾结点的next赋值为NULL
  };
};

int main() {
  Node L = {0, NULL};
  Node *lastPoint = &L;
  insert(&L, lastPoint);
  printList(&L);
  return 0;
}
相关推荐
曙曙学编程4 小时前
stm32——独立看门狗,RTC
c语言·c++·stm32·单片机·嵌入式硬件
YS_Geo5 小时前
Redis 深度解析:数据结构、持久化与集群
数据结构·数据库·redis
njxiejing5 小时前
Pandas数据结构(DataFrame,字典赋值)
数据结构·人工智能·pandas
晨非辰5 小时前
#C语言——刷题攻略:牛客编程入门训练(九):攻克 分支控制(三)、循环控制(一),轻松拿捏!
c语言·开发语言·经验分享·学习方法·visual studio
tju新生代魔迷5 小时前
数据结构:单链表以及链表题
数据结构·链表
dragoooon345 小时前
[数据结构——lesson3.单链表]
数据结构·c++·leetcode·学习方法
hsjkdhs5 小时前
数据结构之链表(单向链表与双向链表)
数据结构·链表·指针
陈序猿(代码自用版)6 小时前
【考研C语言编程题】数组元素批量插入实现(含图示+三部曲拆解)
c语言·开发语言·考研
77qqqiqi6 小时前
学习循环语句
c语言
kyle~6 小时前
排序---冒泡排序(Bubble Sort)
c语言·c++·算法