Skip to content

Commit 6489cdb

Browse files
committed
new question added
1 parent 5cacf8d commit 6489cdb

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ TODO:
135135
- [Given a single linked list. Check if it has a loop](/linked-lists/question8.c)
136136
- [Find the starting node of cycle if cycle exists in a given linked list](/linked-lists/question9.c)
137137
- [Suppose there are two single linked lists both of which merge at the same point and become a single linked list. Find the node at which they merge](/linked-lists/question10.c)
138+
- [Alternating split of a given linked list](/linked-lists/question11.c)
138139

139140

140141
## Some important concepts to solve algos better

linked-lists/question11.c

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
Alternating split of a given linked list.
3+
4+
We can use a counter a split at even and odd numbers and move them to new list, but then we have
5+
dont have to create any new list but use the existing one and split it
6+
7+
METHOD:
8+
take two pointers one pointing to head and one to head->next, then keep assigning them the next
9+
node as per the pattern until one of them reaches null. Make the other one also null in the end
10+
Time complexity: O(n)
11+
Space complexity: O(1)
12+
*/
13+
14+
//METHOD
15+
#include <stdio.h>
16+
#include <stdlib.h>
17+
18+
struct node{
19+
int data;
20+
struct node *link;
21+
};
22+
23+
void makeList(struct node *t, int maxCounter, int mul){
24+
int counter = 1;
25+
while(counter <=maxCounter){
26+
t->data = counter*mul;
27+
if(counter == maxCounter){
28+
t->link = NULL;
29+
}else{
30+
t->link = (struct node *)malloc(sizeof(struct node));;
31+
}
32+
t = t->link;
33+
counter++;
34+
}
35+
}
36+
37+
void printList(struct node *head){
38+
if(head){
39+
printf("%d-->", head->data);
40+
printList(head->link);
41+
}
42+
printf("\n");
43+
}
44+
45+
void alternateList(struct node *head1, struct node *head2){
46+
for(;head1 && head2 && head1->link && head2->link && head2->link->link;
47+
head1=head1->link, head2=head2->link){
48+
49+
head1->link = head2->link;
50+
head2->link = head2->link->link;
51+
}
52+
head1->link = head2->link = NULL;
53+
}
54+
55+
int main(){
56+
struct node *head1 = (struct node *)malloc(sizeof(struct node));
57+
struct node *t = head1;
58+
makeList(t,8,10);
59+
struct node *head2 = head1->link;
60+
printList(head1);
61+
alternateList(head1,head2);
62+
printList(head1);
63+
printList(head2);
64+
65+
}

0 commit comments

Comments
 (0)