我正在尝试编写一个函数来删除给定链表中的所有奇数元素,并返回删除了奇数元素的新链表的地址。我发现这个任务非常复杂,如果你能帮助修复或改进我的代码,我会很高兴。
这是我迄今为止所做的:
typedef struct list{
int data;
struct list* next;
} List;
List* removeOddValues(List** source)
{
List* curr= source;
List* prev;
List* odd= NULL;
while (curr)
{
if ((curr->data)%2!=0)
{
insertNodeToEnd(&odd, curr->data);
prev->next = curr->next;
}
else
{
prev = curr;
curr= curr->next;
}
}
return odd;
}
List* createNewNode(int newData, List* next)
{
List* newNode = (List)calloc(1, sizeof(List));
newNode->data = newData;
newNode->next = next;
return newNode;
}
void insertNodeToEnd(List** list, type newData) //insert a new node to list //
{
LNode* newNode = createNewNode(newData, NULL);
list->next= newNode;
}
答案 0 :(得分:0)
List* removeOddValues(List **source){
List *curr = *source;
List even = { .next = NULL };
List *e_curr = &even;
List odd = { .next = NULL };
List *o_curr = &odd;
while(curr){
List *next = curr->next;
curr->next = NULL;
if(curr->data % 2)// != 0, odd
o_curr = o_curr->next = curr;//node add to last
else//even
e_curr = e_curr->next = curr;
curr = next;
}
*source= even.next;//update source
return odd.next;
}