将新节点作为头部推入c后节点的名称是什么?

时间:2018-06-13 09:34:55

标签: c linked-list

我开始学习链表。我已将代码粘贴到下方。我有一个疑问。当我在前面插入一个节点时,我把它作为头部。因此,每当我想要打印时,我都会调用打印列表(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);
}

3 个答案:

答案 0 :(得分:0)

Head将永远是您的第一个列表节点。如果您想要访问第二个,您将使用head->next

在列表中添加新元素时,当前节点将成为新节点的下一个指针,新节点指针将成为头部。

如果您想要访问第三个,那么您需要访问新头的下一个指针的下一个指针,这使得head->next-next

答案 1 :(得分:0)

如果我想要从第二个节点打印怎么办?这个将特定节点地址传递给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节点遍历。

答案 2 :(得分:0)

  

当我在前面插入一个节点时,我把它作为头部。所以,每当我想要   打印,我打电话给打印列表(头)。如果我想从中打印怎么办?   第二个节点?最初我把它命名为head。现在会是什么?

名称head指的是头部,表达式head->next指的是跟随头部的元素等。

  

我还了解到链表中无法进行随机访问。但   我可以从我想要的节点打印。请澄清。

随机访问具有特殊含义。这意味着您能够以有效的方式访问您想要的任何元素,通常使用其索引。真正的链表中没有随机访问权限,因为如果要访问元素n,则需要从头开始,然后查找下一个,然后是下一个,等等。因此,访问元素n的总成本是n个操作。这不是真正有效的,因为访问元素所需的操作数量随着该元素的索引而增加。非常常见的随机访问结构是数组。