gpt4 book ai didi

c - 在c中将新节点插入头后,节点的名称是什么?

转载 作者:行者123 更新时间:2023-11-30 16:30:58 24 4
gpt4 key购买 nike

我开始学习链表。我已将我的代码粘贴在下面。我有一个疑问。当我在前面插入一个节点时,我将其作为头。所以每当我想打印时,我都会调用 printlist(head)。如果我想从第二个节点打印怎么办?最初我将其命名为 head。现在会是什么?我还了解到链表中不可能进行随机访问。但我可以从任何我想要的节点进行打印。请澄清。

#include <stdlib.h>
#include <stdio.h>

struct node{
char data;
struct node* next;
};

void printlist(struct node* n)
{
while(n!=NULL)
{
printf("%c\n",n->data);
n=n->next;
}
}

void InsertNodeAtFirst(struct node** head_ref)
{
printf("Node insertion at first\n");
struct node* newnode = (struct node*)malloc(sizeof(struct node*));
newnode->data='a';
newnode->next= *head_ref;
*head_ref = newnode;
printf("\n");
printlist(newnode);
}

void InsertNodeAfter(struct node* previous_node)
{
if(previous_node==NULL)
printf("Previous node cannot be blank or NULL\n");

printf("Node insertion at middle\n");
struct node* middlenode = (struct node*)malloc(sizeof(struct node*));
middlenode->data='c';
middlenode->next=previous_node->next;
previous_node->next = middlenode;
printf("\n");
printlist(previous_node);
}

void InsertNodeAtEnd(struct node** LastNode)
{
printf("Node insertion at End\n");
struct node* newnode = (struct node*)malloc(sizeof(struct node*));
struct node* last = *LastNode;

newnode->data='f';
newnode->next=NULL;

while(last->next!=NULL)
{
last=last->next;
}

last->next=newnode;
printf("\n");

}

int main(void)
{
struct node* head = (struct node*)malloc(sizeof(struct node*));
struct node* second = (struct node*)malloc(sizeof(struct node*));
struct node* third = (struct node*)malloc(sizeof(struct node*));

head->data='b';
head->next=second;
second->data='d';
second->next=third;
third->data='e';
third->next=NULL;

printlist(head);
InsertNodeAtFirst(&head);
InsertNodeAfter(head);
InsertNodeAtEnd(&head);
printlist(head);
}

最佳答案

如果我想从第二个节点打印怎么办?为此将特定节点地址传递给 printlist()功能。

例如,在主函数中,创建链接列表后询问用户要从哪个节点打印。比方说n=2

例如

InsertNodeAtFirst(&head);

struct node *temp = head;

/* make temp to point to the node which you want */

/* Find particular node address from where you want to print */

for(int row= 0; row < n; row++){

   if(temp->next != NULL)

temp = temp->next;

}

现在调用 printlist()作为

printlist(temp);

我还了解到,在链表中随机访问是不可能的?只有当您知道该节点的地址时才有可能,并且要获得该地址,您必须从 head 开始遍历节点。

关于c - 在c中将新节点插入头后,节点的名称是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50833877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com