每日一题——第四十六题

在c语言中实现在已知链表中的第三个位置插入数字为a的程序

#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;  
}
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值