每日一题——第四十六题

在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;  
}
相关推荐
顾晨阳——14 分钟前
C/C++字符串
c语言·c++·字符串
Nix Lockhart1 小时前
《算法与数据结构》第七章[算法4]:最短路径
c语言·数据结构·学习·算法·图论
坚持编程的菜鸟4 小时前
LeetCode每日一题——在区间范围内统计奇数数目
c语言·算法·leetcode
qiuiuiu4135 小时前
正点原子RK3568学习日志6-驱动模块传参
linux·c语言·开发语言·单片机·学习
盛小夏5 小时前
从零开始学C语言:小白也能轻松上手
c语言
陌路206 小时前
C语言基础入门阶段
c语言
胖咕噜的稞达鸭6 小时前
二叉树搜索树插入,查找,删除,Key/Value二叉搜索树场景应用+源码实现
c语言·数据结构·c++·算法·gitee
清风wxy7 小时前
C语言基础数组作业(冒泡算法)
c语言·开发语言·数据结构·c++·windows·算法
仲星(._.)7 小时前
C语言:自定义类型
c语言·开发语言
懒羊羊不懒@8 小时前
算法入门数学基础
c语言·数据结构·学习·算法