Skip to content

Commit 7bcb617

Browse files
add problem 328 add test function
1 parent f6af21a commit 7bcb617

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

C/301-350/328-Odd-Even-Linked-List.c

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*
2+
* Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
3+
*
4+
* You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
5+
*
6+
* Example:
7+
* Given 1->2->3->4->5->NULL,
8+
* return 1->3->5->2->4->NULL.
9+
*
10+
* Note:
11+
* The relative order inside both the even and odd groups should remain as it was in the input.
12+
* The first node is considered odd, the second node even and so on ...
13+
*/
14+
#include
15+
#include "../headers/problem_301_350.h"
16+
17+
struct ListNode *oddEvenList(struct ListNode *head) {
18+
if (head == NULL || head->next == NULL || head->next->next == NULL) {
19+
return head;
20+
}
21+
22+
struct ListNode *pOddHead = head, *pEvenHead = head->next;
23+
struct ListNode *pOdd = pOddHead, *pEven = pEvenHead, *p = pEven->next;
24+
25+
int count = 3;
26+
while (p!=NULL) {
27+
if (count % 2) {
28+
pOdd->next = p;
29+
pOdd = pOdd->next;
30+
} else {
31+
pEven->next = p;
32+
pEven = pEven->next;
33+
}
34+
p = p->next;
35+
count++;
36+
}
37+
38+
pEven->next = NULL;
39+
pOdd->next = pEvenHead;
40+
return pOddHead;
41+
}
42+
43+
void testOddEvenList() {
44+
int a1[4] = {1, 2, 3, 4};
45+
int a2[2] = {1, 2};
46+
int a3[4] = {1};
47+
struct ListNode *p;
48+
49+
p = createList(a1, 4);
50+
printList(oddEvenList(p));
51+
52+
p = createList(a2, 2);
53+
printList(oddEvenList(p));
54+
55+
p = createList(a3, 1);
56+
printList(oddEvenList(p));
57+
58+
p = NULL;
59+
printList(oddEvenList(p));
60+
61+
}

0 commit comments

Comments
 (0)