您好我试图通过PID编号按升序将我创建的结构插入到列表中。这是我的代码:
#include <stdlib.h> //for malloc and rand
#include <stdio.h>
struct PCB
{
struct PCB *Next_PCB ;
int PID ;
}*head;
struct PCB *ptr, *tmp, *tmp1;
void insert_ordered (struct PCB *, struct PCB *) ;
void print_list(struct PCB *) ;
main()
{
int num_structs, i;
ptr = (struct PCB *) malloc (sizeof (struct PCB)) ;
num_structs = 10 + (rand() % 10) ;
for ( i = 0 ; i < num_structs ; i++)
{
tmp = (struct PCB *) malloc (sizeof(struct PCB)) ;
tmp->PID = rand() % 20 ;
tmp->Next_PCB = NULL ;
insert_ordered(ptr, tmp) ;
}
print_list(ptr);
}
void insert_ordered (struct PCB *Head, struct PCB *Add)
{
if (Head->Next_PCB == Head) {
Head = Add;
}
}
void print_list(struct PCB *Head)
{
while (Head != NULL) {
if (Head->Next_PCB != NULL) {
printf("PID: %d\n", Head->PID);
Head = Head->Next_PCB;
} else {
printf("PID: %d\n", Head->PID);
break;
}
}
}
即使insert_ordered()
似乎应该在添加元素之前打印一次,但它不会显示输出:
PID:0
另外,我如何正确地将元素插入到LinkedList中?我目前有:
while (Head != NULL) {
if (Head->Next_PCB != NULL) {
if (Add->PID > Head->PID) {
Head = Head->Next_PCB;
printf("pid bigger: %d than current pid: %d\n", Add->PID, Head->PID);
} else if (Add->PID == Head->PID) {
//Head->Next_PCB = Add;
printf("adding pid equal: %d to current pid: %d\n", Add->PID, Head->PID);
} else if (Add->PID < Head->PID) {
//Head->Next_PCB = Add;
printf("adding pid smaller: %d than current pid: %d\n", Add->PID, Head->PID);
}
} else {
Head->Next_PCB = Add;
}
}
不能正常工作。这可能是我的初始if语句无法正确捕获的结果,但无论哪种方式我都难以接受。
提前致谢,SOF。
答案 0 :(得分:1)
这应该这样做:
#include <stdlib.h> /* malloc, rand */
#include <stdio.h> /* printf */
#include <assert.h> /* assert */
struct PCB
{
struct PCB *Next_PCB ;
int PID ;
};
struct PCB *List, *tmp;
void insert_ordered (struct PCB *) ;
void print_list(struct PCB *) ;
main()
{
int num_structs, i;
num_structs = 10 + (rand() % 10) ;
for ( i = 0 ; i < num_structs ; i++)
{
tmp = (struct PCB *) malloc (sizeof(struct PCB)) ;
tmp->PID = rand() % 20 ;
printf("%d ", tmp->PID);
tmp->Next_PCB = NULL ;
insert_ordered(tmp) ;
printf("\n");
print_list(List);
printf("\n");
}
print_list(List);
}
void insert_ordered (struct PCB *Add)
{
struct PCB *Runner = List;
if (List == NULL || Add->PID < List->PID) {
Add->Next_PCB = List;
List = Add;
return;
}
while (Runner->Next_PCB && Add->PID > Runner->Next_PCB->PID){
Runner = Runner->Next_PCB;
}
if (Runner->Next_PCB && Add->PID <= Runner->PID)
{
Add->Next_PCB = Runner->Next_PCB;
Runner->Next_PCB = Add;
}
else
{
Add->Next_PCB = Runner->Next_PCB;
Runner->Next_PCB = Add;
}
}
void print_list(struct PCB *Head)
{
while (Head != NULL) {
if (Head->Next_PCB != NULL) {
printf("PID: %d\n", Head->PID);
Head = Head->Next_PCB;
} else {
printf("PID: %d\n", Head->PID);
break;
}
}
}