如何访问此链接列表中的最后一个节点。由于最后一次循环内部条件不满意,无法访问最后一个节点。请为其提供一些解决方案 [英] How can i access the last node in this linked list.Last node is not reachable due to unsatisfied condition inside last while loop.Please suggest some solutions to it

查看:79
本文介绍了如何访问此链接列表中的最后一个节点。由于最后一次循环内部条件不满意,无法访问最后一个节点。请为其提供一些解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

typedef struct Node
{
    int info;
    struct Node *next;
}node;

void insert(node *ptr,int val)
{
    while(ptr->next!=NULL)
    {
        ptr=ptr->next;
    }
    ptr->next=(node *)malloc(sizeof(node));
    ptr=ptr->next;
    ptr->info=val;
    ptr->next=NULL;
}

int main()
{
    node *ptr,*start;
    start=(node*)malloc(sizeof(node));
    start->next=NULL;
    int a[10]={5,10,15,20,25,30,35,40,45,50};
    int pos=1,item,i,flag;
    for(i=0;i<10;i++)
    insert(start,a[i]);
    printf("Enter the item to be searched for\n");
    scanf("%d",&item);
    ptr=start->next;
    while(ptr->next!=NULL)
    {
        if(ptr->info==item)
        {
            flag=1;
            break;
        }
        else
        {
            pos++;
            flag=0;
            ptr=ptr->next;
        }
    }
    if(flag==1)
    printf("\nElement found at position %d
    \n",pos);
    else
    printf("\nElement not found in the list");
    getch();
}

推荐答案

而不是你的while循环:

Instead of your while loop:
while(ptr->next!=NULL)



你应该使用


You should use

while( ptr != NULL)



ptr是指向要检查并与项目进行比较的当前节点的指针。所以ptr必须是非空的,而不是ptr-> next。


ptr is the pointer to the current node that you want to inspect and compare with the item. So ptr must be non-null, and not ptr->next.


试试这个:



Try this instead:

int pos = 0;
int flag = 0;
node* ptr = start;
while(ptr != NULL)
{
    if(ptr->info == item)
    {
        flag = 1;
        break;
    }
    else
    {
        ++pos;
        ptr = ptr->next;
    }
}





Ian。



Ian.


这篇关于如何访问此链接列表中的最后一个节点。由于最后一次循环内部条件不满意,无法访问最后一个节点。请为其提供一些解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆