我的思路:
1.将链表遍序,找到链表长度,和尾部
2.将所有的偶数节点依次转移到尾部
struct ListNode* oddEvenList(struct ListNode* head) {
if(!head)
{
return head;
}
struct ListNode* end = head;
int listSize = 1;
while(end->next)
{
end = end->next;
listSize++;
}
printf("%d ",listSize);
struct ListNode* cursor = head;
struct ListNode* temp = NULL;
int operationNum = 0;
while(operationNum < (listSize / 2))
{
temp = cursor->next;
if(!temp->next)
{
break;
}
cursor->next = temp->next;
end->next = temp;
end = end->next;
end->next = NULL;
cursor = cursor->next;
temp = NULL;
printf(" hello!");
operationNum++;
}
return head;
}
更好的思路:
1.奇数链表排序
2.偶数链表排序
3.奇数链表的尾部放在偶数链表的头部
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* oddEvenList(struct ListNode* head) {
if (head == NULL) return NULL;
if (head->next == NULL || head->next->next == NULL) return head;
struct ListNode*tmp1 = head, *tmp2 = head -> next, *l2 = tmp2;
while (tmp1->next != NULL && tmp2->next != NULL)
{
tmp1 -> next = tmp1 -> next -> next;
tmp1 = tmp1 -> next;
tmp2 -> next = tmp2 -> next->next;
tmp2 = tmp2 -> next;
}
tmp1-> next = l2;
return head;
}