我正在尝试用C语言在链表的开头插入一个newNode。我尝试过其他方法,比如从insertAtBeginning函数中重新获取newNode,然后在主函数&这很好。但我想做的是为这个案例使用一个void函数,并更改那里不起作用的头。这是完整的代码:
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void linkedListTraversal(struct Node *ptr)
{
while (ptr != NULL)
{
printf("element: %dn", ptr->data);
ptr = ptr->next;
}
}
void insertAtBeginning(struct Node *head, int data)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = head;
head = newNode;
}
void insertAtIndex(struct Node *head, int data, int index)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp = head;
int i = 0;
while (i < index - 1)
{
temp = temp->next;
i++;
}
newNode->data = data;
newNode->next = temp->next;
temp->next = newNode;
}
void insertAtEnd(struct Node *head, int data)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp = head;
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = newNode;
newNode->data = data;
newNode->next = NULL;
}
void insertAfterNode(struct Node *previous, int data)
{
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = previous->next;
previous->next = newNode;
}
int main()
{
struct Node *head;
struct Node *second;
struct Node *third;
struct Node *fourth;
// Allocate memory for the nodes of the linkedLists in the heap
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));
fourth = (struct Node *)malloc(sizeof(struct Node));
// Link first and second nodes
head->data = 12;
head->next = second;
// Link second and third nodes
second->data = 98;
second->next = third;
// Link third and fourth nodes
third->data = 38;
third->next = fourth;
// Terminate the linkedList at the fourth node
fourth->data = 37;
fourth->next = NULL;
printf("Linked list before insertionn");
linkedListTraversal(head);
insertAtBeginning(head, 20);
// insertAtIndex(head, 22, 3);
// insertAtEnd(head, 110);
// insertAfterNode(second, 27);
printf("Linked list after insertionn");
linkedListTraversal(head);
return 0;
}
在这里,我还使用了在链表中插入的其他情况,所有情况都很好,而不仅仅是insertAtBeginning函数:(任何帮助都将是巨大的。
head是列表的入口点。在开头插入一个元素应该使头指向这个新元素。要从void函数中执行此操作,您必须传递head的地址,以便函数修改head:
void insertAtBeginning(struct Node **head, int data)
{
struct Node *newNode = malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
因此,对函数的调用将是:
insertAtBeginning(&head, 20);
另一种解决方案是让函数返回head的新地址。
附言:我们没有在C中强制转换malloc的返回,我们应该检查它是否成功。