题目链接:https://leetcode-cn.com/leetbook/read/linked-list/fe0kj/
这道题意思说是第i个链表结点,如果i是奇数,那么i位于前面的链表,如果i是偶数则位于后面的链表,代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* oddEvenList(struct ListNode* head){
if(head==NULL || head->next == NULL){
return head;
}
struct ListNode* oddHead = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* evenHead = (struct ListNode*)malloc(sizeof(struct ListNode));
oddHead->next = NULL;
evenHead->next = NULL;
struct ListNode* o = oddHead;
struct ListNode* e = evenHead;
struct ListNode* h = head;
int len = 0;
while(h){
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = h->val;
newNode->next = NULL;
len++;
if(len%2){
o->next = newNode;
o = newNode;
}else{
e->next = newNode;
e = newNode;
// printf("%d",e->val);
}
h = h->next;
}
o->next = evenHead->next;
return oddHead->next;
}