-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpartition-list.c
90 lines (87 loc) · 2.16 KB
/
partition-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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//Problem
/*Given a linked list and a dataue x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.*/
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
typedef struct node listnode;
void insertAtEnd(struct node **s,int d)
{
struct node *new=(struct node *)malloc(sizeof(struct node));
struct node *curr=(struct node *)malloc(sizeof(struct node));
curr=*s;
while(curr->next!=NULL)
{
curr=curr->next;
}
new->data=d;
new->next=NULL;
curr->next=new;
}
listnode* partition(listnode* A, int B) {
listnode *curr=A;
listnode *temp1=(listnode *)malloc(sizeof(listnode));
//temp1=A;
listnode *temp2=temp1,*prev=(listnode *)malloc(sizeof(listnode)),*prev1=prev;
int flag=0;
if(A==NULL||A->next==NULL)
return A;
while(curr)
{
if(curr->data<B&&flag==0)
{
temp1->data=curr->data;
curr=curr->next;
flag=1;
}
else if(curr->data<B)
{
while(curr&&curr->data<B){
listnode *new1=(listnode *)malloc(sizeof(listnode));
new1->data=curr->data;
new1->next=NULL;
temp1->next=new1;
curr=curr->next;
temp1=temp1->next;
}
}
else{
prev->next=curr;
prev=prev->next;
curr=curr->next;
}
}
prev->next=NULL;
temp1->next=prev1->next;
//temp2=temp2->next;
if(B==(A->data))
temp2=temp2->next;
return temp2;
}
int main()
{
struct node *s=(struct node *)malloc(sizeof(struct node));
insertAtEnd(&s,1);
insertAtEnd(&s,2);
insertAtEnd(&s,3);
insertAtEnd(&s,4);
insertAtEnd(&s,5);
insertAtEnd(&s,6);
insertAtEnd(&s,2);
insertAtEnd(&s,1);
insertAtEnd(&s,0);
insertAtEnd(&s,10);
s=partition(s,3); //3 mean group of three
while(s!=NULL)
{
printf("%d ",s->data);
s=s->next;
}
}