328奇偶链表

328.奇偶链表

下面是题目

下面是题目给出的模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 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) {

}
};

看了几种方法,都大同小异,无非是代码量的区别,这里给出一种简单易懂的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head)
return head;
ListNode *even = head->next;
ListNode *even_head = head->next;
ListNode *odd = head;
while(1)
{
if(even==NULL||even->next==NULL)
{//遍历完成后,把odd和even的头节点连起来,再return head
odd->next = even_head;
return head;
}
//交错插入,形象的说法就是拉链算法
odd->next = even->next;
odd = odd->next;
even->next = odd->next;
even = even ->next;
}
}
};
-------------本文结束,感谢您的阅读-------------