本文主要是介绍328 Odd Even Linked List,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
超级简单,但是因为好久不写链表了,贡献了好多RE。。。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (head == NULL||head->next==NULL)
return head;
ListNode *odd = NULL, *even = NULL;
ListNode *p1 = NULL, *p2 = NULL;
int i, j;
i = 1;
j = 1;
int n =1;
while (head)
{
if (n % 2 == 0)
{
if (i == 1)
{
even = head;
p1 = even;
i--;
}
else
{
even->next = head;
even = even->next;
}
// even = even->next;
}
else
{
if (j == 1)
{
odd = head;
p2 = odd;
j--;
}
else
{
odd->next = head;
odd = odd->next;
}
}
head = head->next;
n++;
}
odd->next = p1;
head = p2;
if (even)
even->next = NULL;
return head;
}
};
这篇关于328 Odd Even Linked List的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!