【发布时间】:2017-05-10 07:58:47
【问题描述】:
我正在尝试编写一个函数,该函数从给定的链表中删除所有奇数元素,并返回一个新链表的地址,该链表包含已删除的奇数元素。我发现这项任务相当复杂,如果您能帮助修复或改进我的代码,我将非常高兴。
这是我到目前为止所做的:
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;
}
【问题讨论】:
-
1)
List* curr= source;-->List* curr= *source;... 实际插入/删除处理没有做完。 -
@BLUEPIXY 你能解释一下原因吗?
-
source的类型是List **,而不是List * -
我该如何修复我的代码?
-
您的代码未处于更正级别,因为缺少主要部分。我发布了一个代码示例作为答案。
标签: c list linked-list