我想根据编号在已排序的链表中添加一个节点。这是结构:
struct node {
int number;
struct node *next;
}
我能够正确添加到已排序的链表中,但无法改变主意。
不幸的是,我无法更改函数声明的格式,所以这是我的函数:
int create(struct node *head, int number) {
struct node *newNode = malloc(sizeof(struct node));
newNode->number = number;
struct node *current = head;
if (current->number == -1) {
newNode->next = NULL;
*head= *newNode;
return 1;
}
//Checking if head's number is bigger than init
if (current->number > number) {
newNode->next = current;
*head = *newNode;
} else {
while(current->next != NULL && (current->number <= number)) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
return 1;
}
对该函数的调用是(请注意,我也不能更改此设置):
struct node *list;
list = initializeList();
int num;
num = create(list, 5);
num = create(list, 1);
第二个呼叫后,列表应为1-> 5。但它变成1-> 1-> 1-> 1-> .....
编辑:初始化列表的代码:
struct node * initializeList() {
struct node *head;
head = malloc(sizeof(struct node));
head->next = NULL;
head->number = -1;
return head;
}
答案 0 :(得分:1)
我对create
函数进行了一些编辑以解决此问题。
首先,如果列表的开头有number == -1
,则不应分配新的node
,因为您只是替换数字。
第二,如果您需要插入一个节点,则前一个节点需要知道下一个节点的去向,因此您不能仅用新节点替换前一个节点。您需要将前一个节点指向新节点,然后将新节点指向位移节点。或者,您可以将当前节点复制到新节点,然后将新节点的编号放入当前节点,然后将其指向新节点。第二个方法在这里效果更好,因为它不需要改变头部(如果需要在头部,我们就不能这样做)。
int create(struct node *head, int number) {
struct node *current = head;
if (current->number == -1) {
current->number = number;//just replace the number, no need for anything else
return 1;
}
//allocate only if we must insert
struct node *newNode = malloc(sizeof(struct node));
//no longer need to check if head
while(current->next != NULL && (current->number <= number)) {
current = current->next;
}
if(current->next == NULL && current->number < number) {//check if number needs to go at the end
current->next = newNode;
newNode->next = NULL;
newNode->number = number;
} else {
*newNode = *current;//newNode will go after current, but with current's values
current->number = number;//replace current with the number to "insert" it
current->next = newNode;//point to the next node
}
return 1;
}
答案 1 :(得分:-1)
为该节点分配一个索引值,并将其他元素移动一个。我的意思是,您可以在另一个元素的每个值上添加一个,并在一个循环中进行迭代。