c - 链表总是显示为空
问题描述
要求/问题 2
在计算中,进程标识符(通常称为进程 ID 或 PID)是大多数操作系统内核使用的数字,用于唯一标识活动进程。PID 通常是按顺序分配的,从 0 开始并上升到最大值,该最大值因系统而异。创建一个链接列表来存储 PID。要创建新的 PID,createPID()
请使用函数。使用函数将每个 PID 插入到列表开头的列表中
insertPID()
。一旦一个进程完成,该特定的 PID 将被删除,使用该deletePID()
函数。评估将根据以下标准进行:
- 正确编写 C 代码及其结构
- 程序被编译和执行的能力
- 实施正确的编程技术
- 完整的文件和正确的提交
注意:您必须为此作业编写 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;
}
结果总是空列表。需要帮助找出问题所在?
解决方案
问题出在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。
推荐阅读
- windows - 如何在 docker swarm 中重命名 WSL2 docker-desktop 节点
- angular - 类型“typeof”角度上不存在属性
- python - 如何向禁用强制参数的解析器声明可选参数?
- postgresql - postgreSQL json 查询和更新/插入
- flutter - Flutter-尝试从 AssetImage 加载时发生超时
- python - 我想从 Django API 检索数据并将其存储在数据库中
- python-3.x - Flask-Mongoengine 自定义排序比较器
- android - 以 json 格式接收 Microsoft 日期格式
- spring - 当表用作队列时了解@Transactional
- javascript - 为什么空对象不等于 JavaScript 中的空对象?(也是数组)