每日一题——第四十六题

在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;  
}
相关推荐
艾莉丝努力练剑1 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
不知道叫什么呀7 小时前
【C】vector和array的区别
java·c语言·开发语言·aigc
秋说7 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法
秋说10 小时前
【PTA数据结构 | C语言版】字符串插入操作(不限长)
c语言·数据结构·算法
遇见尚硅谷12 小时前
C语言:20250714笔记
c语言·开发语言·数据结构·笔记·算法
koooo~18 小时前
JavaScript 与 C语言基础知识差别
c语言·开发语言·javascript
mit6.82419 小时前
[Nagios Core] 通知系统 | 事件代理 | NEB模块,事件,回调
c语言·开发语言
mit6.82419 小时前
[Nagios Core] 事件调度 | 检查执行 | 插件与进程
c语言·开发语言·性能优化
刃神太酷啦20 小时前
C++ 多态详解:从概念到实现原理----《Hello C++ Wrold!》(14)--(C/C++)
java·c语言·c++·qt·算法·leetcode·面试
弱冠少年20 小时前
ESP-Timer入门(基于ESP-IDF-5.4)
c语言