题解 | #链表的奇偶重排#
链表的奇偶重排
http://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
#include<stdlib.h>
#include<stdio.h>
struct ListNode* oddEvenList(struct ListNode* head ) {
// write code here
//计算节点个数
struct ListNode *p1 = head;
int count = 0;
while(p1 != NULL)
{
p1 = p1->next;
count++;
}
if(count == 2|| count == 1||count == 0) return head;
int old = count/2,even = (count+1)/2;
struct ListNode *p2;
struct ListNode *newhead = (struct ListNode*)malloc(sizeof(struct ListNode));
p2 = newhead;
p1 = head;
for(int i = 1;i<even;i++)
{
p2->val = p1->val;
p1 = p1->next->next;
p2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
p2 = p2->next;
}
p2->val = p1->val;
//奇数完
p1 = head->next;
p2->next = (struct ListNode *)malloc(sizeof(struct ListNode));
p2 = p2->next;
for(int i = 1;i<old;i++)
{
p2->val = p1->val;
p1 = p1->next->next;
p2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
p2 = p2->next;
}
p2->val = p1->val;
p2->next = NULL;
//偶数完
return newhead;
}
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
#include<stdlib.h>
#include<stdio.h>
struct ListNode* oddEvenList(struct ListNode* head ) {
// write code here
//计算节点个数
struct ListNode *p1 = head;
int count = 0;
while(p1 != NULL)
{
p1 = p1->next;
count++;
}
if(count == 2|| count == 1||count == 0) return head;
int old = count/2,even = (count+1)/2;
struct ListNode *p2;
struct ListNode *newhead = (struct ListNode*)malloc(sizeof(struct ListNode));
p2 = newhead;
p1 = head;
for(int i = 1;i<even;i++)
{
p2->val = p1->val;
p1 = p1->next->next;
p2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
p2 = p2->next;
}
p2->val = p1->val;
//奇数完
p1 = head->next;
p2->next = (struct ListNode *)malloc(sizeof(struct ListNode));
p2 = p2->next;
for(int i = 1;i<old;i++)
{
p2->val = p1->val;
p1 = p1->next->next;
p2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
p2 = p2->next;
}
p2->val = p1->val;
p2->next = NULL;
//偶数完
return newhead;
}