每日一题——第四十六题

在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;  
}
相关推荐
双叶8369 小时前
(51单片机)矩阵按键密码锁表白(C语言代码编撰)(矩阵按键教程)(LCD1602浅教程)
c语言·开发语言·c++·算法·游戏·矩阵·51单片机
小郝 小郝11 小时前
【C语言】内存函数 (续)
c语言·开发语言·学习
似水এ᭄往昔14 小时前
【C语言】编译和链接
c语言·开发语言
W说编程14 小时前
《UNIX网络编程卷1:套接字联网API》第4章 基本TCP套接字编程
c语言·网络·网络协议·tcp/ip·架构·unix·tcp
南玖yy14 小时前
数据结构C语言练习(设计循环队列)
java·c语言·数据结构
_GR14 小时前
2023年蓝桥杯第十四届C&C++大学B组真题及代码
c语言·c++·蓝桥杯
努力努力再努力wz14 小时前
【c++深入系列】:类和对象详解(下)
java·运维·c语言·开发语言·c++
明月醉窗台15 小时前
Qt 入门 3 之对话框 QDialog(1)
c语言·开发语言·c++·qt
凯强同学18 小时前
第十五届蓝桥杯大赛软件赛省赛Python 大学 C 组:6.挖矿
c语言·python·算法·职场和发展·蓝桥杯
march_birds18 小时前
Zephyr与Linux核心区别及适用领域分析
c语言·开发语言·单片机·系统架构