c - 链表遍历跳过第一个元素

标签 c data-structures linked-list singly-linked-list

我有一个 C 程序可以在链表的开头插入元素,但是当我尝试打印元素时,它总是跳过第一个元素。有人可以指出我在我的程序中做错了什么吗。

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


void PrintElements();
void InsertElement(int x);

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

struct node* HEAD;
struct node* temp;
struct node* temp1;


void PrintElements()
{
    temp1=HEAD;
    while(temp1->next!=NULL)
    {
        printf("\n\r Data %d\n\r",temp1->data);
        printf("\n\r Address %x\n\r",temp1->next);
        temp1=temp1->next;
    }
}

void InsertElement(int x)
{
    struct node* temp=(struct node*)malloc(sizeof(struct node));
    temp->data=x;
    temp->next=HEAD;
    HEAD=temp;

}

int main()
{

    int i, x;
    int n;   //n stores the number of elements to be added to the linked list
    HEAD=NULL; //Assigning HEAD to null when there are no elements in the list
    printf("Enter the number of elements\n");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        printf("\n\rEnter the number");
        scanf("%d",&x);
        InsertElement(x);
        PrintElements();
    }

    return 0;
}

当我更改以下行时

while(temp1->next!=NULL)

while(temp1!=NULL)

程序运行正常,但我仍然不明白为什么。

最佳答案

while(temp1->next!=NULL)

将此更改为

while(temp1 != NULL)

它应该可以正常工作。

原因:我认为它不会打印您输入的第一个元素。

示例:输入:1 2 3

链表形式为:3 -> 2 -> 1 -> NULL 使用的符号:每个数字都是数据,箭头表示指针next

然后当你开始循环时,对于每次迭代:

  • temp1 指向3

  • 的地址
  • temp1 -> next != NULL(当 temp1 -> next 指向 2 的地址时为真)

  • 打印 3temp1 现在指向 2

    的地址
  • temp1 -> next != NULL(当 temp1 -> next 指向 1 的地址时为真)

  • 打印 2temp1 现在指向 1

    的地址
  • temp1 -> next != NULL 这变为 False 因为 temp1 指向 1 的地址> 和 temp1 -> next 为 NULL。

所以我们永远不会进入循环以打印 1

所以正确的做法是使用 temp1 != NULL 因为这将消除上述错误。

关于c - 链表遍历跳过第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41404995/

相关文章:

objective-c - 如何将 NSMutableArray 中的元素放入 C char 中?

c - 并非所有内容都由内核模块正确发送给用户

data-structures - "close over"是什么意思?

c++ - 具有给定级别的二叉树节点数

javascript - 为什么这个 javascript add() 函数会为链表返回节点?

c++ - 哈希表 - 链表数组 - C++

c - 结构中的语法 [c]

c - scandir() 导致段错误,即使有有效的绝对路径?

database - 如何存储信息?数据库、数据结构、日志文件

algorithm - 如何找到单链表的交集