题解 | #链表的奇偶重排#
链表的奇偶重排
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 ) {
if(head == NULL){
return head;
}
// write code here
struct ListNode* p = head;
struct ListNode* q = head->next;
struct ListNode* resul = head;
//偶数
struct ListNode* even = (struct ListNode*)malloc(sizeof(struct ListNode));
even->next = NULL;
struct ListNode* even_start = even;
//奇偶分链
while(p->next!=NULL&&q->next!=NULL){
p->next = q->next;
even->next = q;
p = p->next;
q = p->next;
even = even->next;
}
//临界情况
if(q!=NULL){
even->next = q;
even = even->next;
}else{
even->next = NULL;
}
p->next = even_start->next;
return resul;
}
查看10道真题和解析