-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathOdd Even Linked List.c
70 lines (54 loc) · 1.34 KB
/
Odd Even Linked List.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include<malloc.h>
struct ListNode* insertEnd(struct ListNode *head,int ele){
struct ListNode *p;
p=head;
struct ListNode *node=(struct ListNode *)malloc(sizeof(struct ListNode));
node->val=ele;
// printf("Value: %d ",node->val);
node->next=NULL;
if(p==NULL){
head=node;
return head;
}
while(p->next!=NULL)p=p->next;
p->next=node;
return head;
}
void printList(struct ListNode *head){
struct ListNode*p=head;
while(p!=NULL){
printf("%d ",p->val);
p=p->next;
}
printf("\n");
}
struct ListNode* oddEvenList(struct ListNode* head){
if(head==NULL)return NULL;
struct ListNode *p;
p=head;
int c=0;
struct ListNode *even=NULL;
struct ListNode *odd=NULL;
while(p!=NULL){
if(c%2==0) even= insertEnd(even,p->val);
else odd=insertEnd(odd,p->val);
c++;
// printf("%lld %lld\n",even,odd);
p=p->next;
}
printList(even);
printList(odd);
struct ListNode *evenstart=even;
while(evenstart->next!=NULL)evenstart=evenstart->next;
evenstart->next=odd;
evenstart=even;
printList(evenstart);
return evenstart;
}