gpt4 book ai didi

c - 将节点移动到链表函数的末尾问题

转载 作者:太空宇宙 更新时间:2023-11-04 04:10:49 26 4
gpt4 key购买 nike

我是一名 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;
}

关于c - 将节点移动到链表函数的末尾问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57840635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com