在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) {
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() {
ListNode* head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(3);
head->next->next->next = createNode(4);
insertAtThirdPosition(&head, 5);
printList(head);
return 0;
}