我有一个任务。我获得了一个无法修改的函数声明。
函数声明是 void Insert (Item x, int p, List *L);
我应该在其中更改链表结构 L 的值。
现在,在我的主函数中调用该方法的代码是
struct List *L = malloc(sizeof(List));
Insert(x,p,L);
如何更改我的代码,以便可以传递 struct List 的地址而不是复制它?
就像我说的,我根本无法更改函数声明。
/************************************************ **************************
* 函数名称:插入
* 目的:在列表中插入一个项目。
* 参数: .要插入的项目(Item)
*。在列表中的位置
* 项目应插入的位置 (int)
*。列表的地址 (List *L)
* 要求(先决条件):
*。位置应该是一个非负整数
* 不大于列表的大小。
*。该列表不应该是完整的。
* 确保: .为空将返回 false (0)。
*。 Size 将返回第一个更大的整数
* 比调用前List的大小。
*。在同一位置查看会发现
* 插入的项目。
****************************************************** ******************/
extern void Insert(项目 X, int 位置, List *L);
我尝试过但不起作用的是
头->下一个= L;//将列表中的下一项更改为L
L = 头;//改变L的地址,使其保持链表的头部
最佳答案
我认为这会起作用:
void Insert (Item x, int p, List *L) {
struct List newnode, last = *L;
newnode = (struct List)malloc(sizeof(struct List));
newnode->item = x;
newnode->next = NULL;
if (last == NULL){
if (p == 0) { *L = newnode; }//first node
else { printf("List is empty and index %d does not exist", p); }
} else if (p == 0) {
newnode->next = *L;
*L = newnode;
}
else{
int counter = 0;
while (1) {
if (counter == p) {
newnode->next = last->next;
last->next = newnode;
break;
}
last = last->next;
counter++;
if (last->next == NULL && counter != p){ break; }
}
}
}
关于在没有参数灵活性的情况下更改链表的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32833666/