每日一题——第四十六题

在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;  
}
相关推荐
WL学习笔记14 分钟前
顺序表详解
c语言·数据结构
c++之路1 小时前
CMake 系列教程(一):CMake 基础知识
c语言·开发语言·c++
我还记得那天1 小时前
C语言随机数生成机制与猜数字游戏实现
c语言·开发语言·游戏
万法若空2 小时前
C/C++基本类型表示范围
c语言·开发语言·c++
J2虾虾4 小时前
C 语言 sizeof 完全用法指南
c语言·数据结构·算法
xxwxx__4 小时前
51单片机定时器/计数器中断详解(T0和T1)——从入门到精通
c语言·单片机·嵌入式硬件·51单片机
cft56200_ln4 小时前
TDA4时间同步3 网卡添加虚拟时间戳
c语言·开发语言·arm开发·驱动开发·嵌入式硬件·网络协议
189228048614 小时前
NV091固态MT29F16T08EWLCHD8-QJES:C
c语言·开发语言
AI thought4 小时前
C语言企业项目实战(四)
c语言·单元测试·压力测试·企业项目·工程体系
AI科技星5 小时前
《数术工坊:无穷套娃录》 一部用数学套娃写成的“天书小说”
c语言·开发语言·网络·量子计算·agi