forked from Raushan710/teaching_1
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdivideLL.cpp
More file actions
83 lines (70 loc) · 1.26 KB
/
Copy pathdivideLL.cpp
File metadata and controls
83 lines (70 loc) · 1.26 KB
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
// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
void printList(Node *);
// Function to split the given linked list
// into ratio of p and q
void splitAndPrint(Node *head, int p, int q)
{
int n = 0;
Node *temp;
temp = head;
// Find the length of the list
while (temp != NULL)
{
n += 1;
temp = temp->next;
}
// If ration exceeds the actual length
if (p + q > n)
{
cout << "-1" << endl;
return;
}
temp = head;
while (p > 1)
{
temp = temp->next;
p -= 1;
}
// second head node after splitting
Node *head2 = temp->next;
temp->next = NULL;
// Print first linked list
printList(head);
cout << endl;
// Print second linked list
printList(head2);
}
// Function to print the nodes
// of the linked list
void printList(Node* head)
{
if (head == NULL)
return;
cout << head->data << " ";
printList(head->next);
}
// Driver code
int main()
{
Node* head = new Node(1);
head->next = new Node(3);
head->next->next = new Node(5);
head->next->next->next = new Node(6);
head->next->next->next->next = new Node(7);
head->next->next->next->next->next = new Node(2);
int p = 2, q = 4;
splitAndPrint(head, p, q);
}
// This code is contributed by rutvik_56.