题解 | 链表的奇偶重排
链表的奇偶重排
https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
#include <stdlib.h>
struct ListNode* oddEvenList(struct ListNode* head ) {
// write code here
struct ListNode *p;
p = head;
int total_len = 0;
while (p)
{
total_len++;//求出链表长度
p = p->next;
}
int *odd = (int*)malloc(sizeof(int) * total_len/2 + 1);
int *even = (int*)malloc(sizeof(int) * total_len/2 + 1);
p = head;
int even_len = 0,odd_len = 0;
/* 将奇数位和偶数位的元素分别保存到各自的数组中 */
while (p)
{
odd[odd_len++] = p->val;
p = p->next;
if(!p)
{
break;
}
even[even_len++] = p->val;
p = p->next;
}
//奇数数组和偶数数组依次赋值给链表
p = head;
int i = 0,j = 0;
while (p)
{
for(i=0;i<odd_len;i++)
{
p->val = odd[i];
p = p->next;
}
if(!p)
{
break;
}
for(j=0;j<even_len;j++)
{
p->val = even[j];
p = p->next;
}
}
//释放内存
free(even);
free(odd);
return head;
}
思路:把链表上的奇数位和偶数位分别用两个数组存储起来,最后再利用奇数数组和偶数数组对链表按顺序赋值即可。