每日一题——第四十六题

在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;  
}
相关推荐
八月的雨季 最後的冰吻2 小时前
C--字符串函数处理总结
c语言·前端·算法
Mr_Xuhhh4 小时前
C语言深度剖析--不定期更新的第六弹
c语言·开发语言·数据结构·算法
善 .5 小时前
C语言编译过程
c语言·开发语言
黄卷青灯775 小时前
c语言 #define 详解
c语言·开发语言·define
2023王先生要加油鸭6 小时前
81.C语言中的内存分布
c语言·开发语言
北航最菜大学生6 小时前
数据结构(五)----树(含堆)
c语言·数据结构
pzn25067 小时前
排序进阶(C语言)
c语言·数据结构
宝贝儿好8 小时前
【C++】作用域指针、智能指针、共享指针、弱指针
java·c语言·jvm·c++
Hcoco_me8 小时前
【附答案】C/C++ 最常见50道面试题
java·c语言·c++
MYMOTOE68 小时前
倒推因子分解法——C语言实现
c语言·c++·算法