首页 文章

链表遍历**与(thead!= NULL)**和while(thead-> next!= NULL)之间的差异

提问于
浏览
2

任何人都可以告诉我 while(thead != NULL)while(thead->next !=NULL) 之间有什么区别,因为遍历列表 thead != NULLthead->next 工作时不起作用 . 根据我的理解,head节点只是指向起始节点而不是起始节点本身的指针 .
See this if u have doubt . 这里只是存储地址 .

// thead表示临时头变量以存储地址头指向 .
这是插入的代码 .

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

struct node
{
    int data;
    struct node *next;
};
struct node *head;
void insert(int x)
{
    struct node *temp=(struct node *)malloc(sizeof(struct node));   
    temp->data=x;   
    temp->next=NULL;   
    if(head==NULL)     
    {     
         head=temp;    
    }
    else
    {
        struct node * thead;
        thead=head;  
        while(thead->next!=NULL)
        {
            thead=thead->next;  
        }
        thead->next=temp;
    }
}

void print()
{
    struct node *temp;
    temp=head;
    while(temp!=NULL)
    {

        printf("%d",temp->data);
            temp=temp->next;
    }
}
int main()
{
    head=NULL;
    int i,n,x;
    printf("enter number of nodes");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        printf("enter no");
        scanf("%d",&x);
        insert(x);
    }
    print();
}

If we replace thead ->next != NULL by thead !=NULL then dev c++ stops working.Vice versa happens in the printf for traversal ...

那么有人可以回答上述两者之间的差异吗?

此外,头节点是第一个包含数据和地址的节点,还是只存储上图中的地址?

此外,如果头节点只是一个存储地址的指针,那么我们如何才能访问thead-> next?

什么时候是一个指向结构NULL的指针?

谢谢

2 回答

  • 0

    使用 print() ,代码不需要记住循环后的最后一个节点地址

    temp=head;
    while(temp!=NULL) {
        printf("%d",temp->data);
        temp=temp->next;
    }
    // temp == NULL at this point and code does not care what the last node was.
    

    使用 insert() ,代码确实需要记住循环后的最后一个节点地址 .

    // First handle special case where the head of the list is NULL
    // otherwise ....
    while(thead->next!=NULL) {
        thead = thead->next;  
    }
    // temp->next == NULL at this point
    // Code can use `thead` to access the last node's members.
    thead->next = temp;
    

    头节点是第一个包含数据和地址的节点,还是只存储上图中的地址?

    struct node *head 是一个指针 . 当 head != NULL 时,它指向包含数据和下一个指针的frist节点 .

    如果头节点只是一个存储地址的指针,那么我们如何才能访问thead-> next?

    thead 使用 head 初始化 . 通过取消引用 thead ,代码可以访问该节点的成员,包括 .next .

    什么时候是一个结构为NULL的指针?

    问题不清楚 . 当 struct 的值等于 NULL 时,它指向 NULL . 这通常是链表代码中的结尾 .

  • 1

    现在我已经明白......对于那些仍然被困的人我正在写这个......

    当我使用(thead!= NULL)时,thead指针实际上指向列表中的每个元素 . 当它到达最后一个元素时,它仍然遍历到下一个NULL元素,不像(thead-> next!= NULL)它停在链表的最后一个元素 .

    在打印的情况下,我们需要打印列表中的所有值,因此我们使用while(thead!= NULL),因为我们还需要打印最后一个元素 . 对于遍历,我们只需要使指针指向最后一个节点,这样我们就可以了可以停在它并且不会遍历,直到我们到达NULL指针 .

    我们无法取消引用NULL,因此出现了错误 .

相关问题