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

标签 c linked-list

我开始学习链表。我已将我的代码粘贴在下面。我有一个疑问。当我在前面插入一个节点时,我将其作为头。所以每当我想打印时,我都会调用 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/

相关文章:

传递给函数的 C 可变参数

c - Base64 解码 - 字符串长度不正确

java - 循环双向链表 addToHead 并打印

C++ 排序双向链表 : Problems inserting in middle of list

使用链表比较 C 语言中的多米诺骨牌并将其排序

C 数组链表,将一个数组链表分配给另一个数组链表

c - 如何在不进行类型转换的情况下通过乘法避免整数溢出?

c while循环入口

C 中的检查循环 - scan() 未在第二次运行时运行

java - 我一直坚持删除()