每日一题——第四十六题

在c语言中实现在已知链表中的第三个位置插入数字为a的程序

c 复制代码
#include <stdio.h>  
#include <stdlib.h>  
  
// 定义链表节点结构体  
typedef struct ListNode {  
    int val;  
    struct ListNode *next;  
} ListNode;  
  
// 创建一个新节点  
ListNode* createNode(int val) {  
    ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));  
    if (!newNode) {  
        printf("Memory allocation failed!\n");  
        exit(1);  
    }  
    newNode->val = val;  
    newNode->next = NULL;  
    return newNode;  
}  
  
// 在链表的第三个位置插入节点  
void insertAtThirdPosition(ListNode** head, int a) {  
    if (*head == NULL || (*head)->next == NULL || (*head)->next->next == NULL) {  
        // 如果链表长度小于3,则不能直接插入到第三个位置  
        printf("The list does not have enough nodes to insert at the third position.\n");  
        return;  
    }  
  
    ListNode* newNode = createNode(a);  
    ListNode* temp = *head;  
  
    // 移动到第二个节点  
    temp = temp->next;  
  
    // 插入新节点到第三个位置  
    newNode->next = temp->next;  
    temp->next = newNode;  
}  
  
// 打印链表  
void printList(ListNode* head) {  
    ListNode* temp = head;  
    while (temp != NULL) {  
        printf("%d -> ", temp->val);  
        temp = temp->next;  
    }  
    printf("NULL\n");  
}  
  
// 主函数  
int main() {  
    // 创建一个简单的链表 1 -> 2 -> 3 -> 4  
    ListNode* head = createNode(1);  
    head->next = createNode(2);  
    head->next->next = createNode(3);  
    head->next->next->next = createNode(4);  
  
    // 在第三个位置插入值为5的节点  
    insertAtThirdPosition(&head, 5);  
  
    // 打印链表  
    printList(head);  
  
    // 释放链表内存(略)  
  
    return 0;  
}
相关推荐
Rabitebla19 小时前
【C++】string 类:原理、踩坑与对象语义
linux·c语言·数据结构·c++·算法·github·学习方法
宣宣猪的小花园.21 小时前
C语言重难点全解析:内存管理到位运算
c语言·开发语言·单片机
三品吉他手会点灯1 天前
C语言学习笔记 - 20.C编程预备计算机专业知识 - 变量为什么必须的初始化【重点】
c语言·笔记·学习
JasmineX-11 天前
数据结构(笔记)——双向链表
c语言·数据结构·笔记·链表
爱编码的小八嘎1 天前
C语言完美演绎9-7
c语言
澈2071 天前
深耕进阶 Day1:C 与 C++ 核心差异 + C++ 入门基石
c语言·开发语言·c++
love530love1 天前
Windows Podman Machine 虚拟硬盘迁移完整指南:从 C 盘到非系统盘
c语言·人工智能·windows·podman
Felven1 天前
C. Need More Arrays
c语言·开发语言
love530love1 天前
Podman Machine 虚拟硬盘迁移实战二:用 Junction 把 vhdx 从 C 盘搬到其他盘
c语言·开发语言·人工智能·windows·wsl·podman·podman machine
代码中介商1 天前
C语言预处理指令深度解析:从宏定义到条件编译
c语言·开发语言