我是C编程的学生,我现在只是在学习基础知识。我需要编写一个函数,在输入中给定链表,将包含 5 和 3 倍数的节点放在列表的末尾。我正在尝试使用一种递归方法,但程序崩溃了。 练习指南说我不能删除节点,然后在列表末尾重新创建它们。我必须修改指针。
编辑:调试器说这是一个分段错误问题。
下面是输入中给出的调试错误的图像,其中包含此列表 (15 -> 7 -> 2 -> 1 -> 30 -> 25 -> 10(: SegFaultdebug
//node is a type I defined for linked list nodes
node *multipleOf3And5ToTail(node *head){
node *temp2=head;
if((head->val%3==0)&&(head->val%5==0)&&head!=NULL){
while(temp2->next!=NULL){
temp2=temp2->next;
}
temp2->next=head;
head=head->next;
temp2->next->next=NULL;
head->next=mul5e3coda(head->next);
}
else{
while(((head->val%3!=0)||(head->val%5!=0))&&head!=NULL){
head=head->next;}
if((head->val%3==0)&&(head->val%5==0)&&head!=NULL){
head=mul5e3coda(head);
}
}
return head;
}
谢谢大家!我解决了自己编写不同代码的问题。
bool isMultipleOf3And5(int n){
return n%3==0 && n%5==0;
}
node* getTail(node *head){
while(head->next != NULL)
head = head->next;
return head;
}
node* multipleOf3And5ToTail(node *head){
node *prev=NULL, *curr=head, *succ=NULL, *tail=NULL, *firstMultipleInTail=NULL;
while(curr != NULL){
while(!isMultipleOf3And5(curr->val) && curr->next != NULL){
prev = curr;
curr = curr->next;
succ = curr->next;
}
if(curr == firstMultipleInTail || curr->next == NULL)
break; // if so, we can stop
if(tail == NULL) {
// needed to check when we arrive again to it
firstMultipleInTail = curr;
tail = getTail(curr);
}
// put the multiple of 3 and 5 in tail
tail->next = curr;
// to adjust pointers:
// if the multiple was in head, we advance head
if(prev == NULL) head = head->next;
// else we link the prev to the succ
else prev->next = succ;
// advance curr
curr = curr->next;
// set the end of list to NULL
tail->next->next = NULL;
// update the tail
tail = tail->next;
}
return head;
}