gpt4 book ai didi

c - 分离链表中的偶数和奇数节点

转载 作者:行者123 更新时间:2023-11-30 19:36:19 24 4
gpt4 key购买 nike

我需要在 C 中分离链表中的偶数和奇数节点。

示例:

原始列表:3,1,8,2,5,6
更改后:8,2,6,3,1,5

当头列表数据是奇数时,我遇到一个问题,它正在删除偶数。

示例:

原始列表:3,1,8,2,5,6
更改后:3,1,5

typedef struct Node {
int data; // store information
struct Node * next; //referance to the next node
}Node;

Node * create(Node * L, int value)
{
Node *current = L ,* new_node = (Node*)malloc(sizeof(Node)); // create and allocate a node
new_node->data = value;
new_node->next = NULL;
if (L == NULL)
{
L = new_node;
current = new_node;
}
else
{
while (current->next != NULL)
current = current->next;
current->next = new_node;
current = new_node;
}
return L;
}

Node * Change_Even_Odd(Node * L)
{
Node *oddhead = NULL, *evenhead = NULL, *lastodd = NULL, *lasteven = NULL, *current = L;
while (current != NULL)
{
// if current is even node
if (current->data % 2 == 0)
{
if (evenhead == NULL)
{
evenhead = current;
lasteven = current;
}
else
{
lasteven->next = current; // to connect the node to the list in the end
lasteven = current; // final list
}
}
else
{
// if current is odd node
if (oddhead == NULL)
{
oddhead = current;
lastodd = current;
}
else
{
lastodd->next = current;
lastodd = current;
}

}
current = current->next;
}

if (evenhead != NULL) // to put the even node in the head list
L = evenhead;
if (lasteven != NULL) // link the odd nodes to the even nodes
lasteven->next = oddhead;
if (lastodd != NULL) //end of list
lastodd->next = NULL;

return L;

}


void Print_List(Node * head)
{
while (head != NULL)
{
printf("%4d", head->data);
head = head->next;
}
}

int main()
{
Node * list = NULL; //empty linked list
srand(time(NULL));
int i, size = rand() % 10 + 1;
for (i = 0; i < size; i++)
list = create(list, rand() % 10 + 1);
printf("%d\n",size);
Print_List(list);
printf("\n");
Change_Even_Odd(list);
Print_List(list);
printf("\n");
}

最佳答案

Change_Even_Odd(list); 应该是 list = Change_Even_Odd(list); (我已经指出了。) – BLUEPIXY

关于c - 分离链表中的偶数和奇数节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41072773/

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