首页 > 解决方案 > 链表总是显示为空

问题描述

要求/问题 2
在计算中,进程标识符(通常称为进程 ID 或 PID)是大多数操作系统内核使用的数字,用于唯一标识活动进程。PID 通常是按顺序分配的,从 0 开始并上升到最大值,该最大值因系统而异。创建一个链接列表来存储 PID。要创建新的 PID,createPID()请使用函数。

使用函数将每个 PID 插入到列表开头的列表中insertPID()。一旦一个进程完成,该特定的 PID 将被删除,使用该deletePID()函数。

评估将根据以下标准进行:

  1. 正确编写 C 代码及其结构
  2. 程序被编译和执行的能力
  3. 实施正确的编程技术
  4. 完整的文件和正确的提交

注意:您必须为此作业编写 C 编程代码。

我已经创建了一个代码:

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

struct node
{
    int info;
    struct node *link;
};

void createPID ();
void insertPID (struct node *start,int x);
struct node * deletePID (struct node * start,int x);
void displayPID(struct node *start);
struct node * start;

int main()
{
    createPID();
    insertPID(start,0);
    insertPID(start,1);
    insertPID(start,2);
    displayPID(start);
    start=deletePID(start, 3);
    displayPID(start);

}

void createPID(){
    struct node *start = NULL;
}


void displayPID(struct node *start)
{
    struct node *p;
    if(start == NULL)
    {
        printf("List is empty\n");
        return;

    }
    printf("List is :");
    p=start;
    while(p!=NULL)
    {
        printf("%d\t",p->info);
        p=p->link;
     } 
     printf("\n");
}
/*End of displayList()*/

void insertPID(struct node * start, int data)
{
    struct node *temp,*p;

    p=start;
    while (p!=NULL)
    {
        if(p->link==NULL)
        break;
        p=p->link;
    }
    temp=(struct node *)malloc (sizeof (struct node));
    temp->info=data;
    if(p==NULL)
    start=temp;
    else
    {
    temp->link= p->link;
    p->link= temp;
    }
}

struct node* deletePID(struct node * start,int x){
    struct node *temp, *p;
    if(start == NULL)
    {
        printf("List is empty\n");
        return start;
    }
    /*Deletion of first node */
    if(start->info == x)
    {
        temp=start;
        start= start->link;
        free(temp);
        return start;
    }

    /*Deletion in between or at the end */
    p=start;
    while (p->link != NULL)
    {
        if (p-> link -> info== x)
        break;
        p=p->   link;
    }
    if(p->link==NULL)
    printf("Element %d not in list \n\n",x);
    else 
    {
        temp=p->link;
        p->link=temp->link;
        free (temp);
    }
    return start;

}

结果总是空列表。需要帮助找出问题所在?

标签: cdata-structures

解决方案


问题出在insertPID功能上。start由于函数的参数是局部变量,它隐藏了全局start和下面的行

start = temp;

仅修改 local start, globalstart不受影响,始终为 NULL。

如果要更新start指针,则需要通过指针对指针传递:

void insertPID (struct node **start,int x);
//...
insertPID(&start,0);
insertPID(&start,1);
insertPID(&start,2);
//...
void insertPID(struct node ** start, int data)
{
    //...
    p=*start;
    //...
    if(p==NULL)
        *start=temp;
    //...
}

void createPID(){
    struct node *start = NULL;
}

我假设这个函数想将start(全局)设置为 0 ?所以应该是:

void createPID(){
    start = NULL;
}

您的版本引入了局部start变量,因此全局不受影响。

但是这里的调用createPID是多余的,因为start全局变量在main开始执行之前被初始化为 0。


推荐阅读