-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlec5_8.cpp
More file actions
143 lines (117 loc) Β· 2.78 KB
/
Copy pathlec5_8.cpp
File metadata and controls
143 lines (117 loc) Β· 2.78 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
//{ Driver Code Starts
#include <bits/stdc++.h>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
/*
// Redirecting input from file
freopen("/Users/debojyoti.mandal/expt/input.txt", "r", stdin);
// Redirecting output to file
freopen("/Users/debojyoti.mandal/expt/output.txt", "w", stdout);
*/
struct node {
int data;
struct node* next;
node(int x) {
data = x;
next = NULL;
}
};
/* Function to print linked list */
void printList(struct node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
// } Driver Code Ends
/*
Reverse a linked list
The input list will have at least one element
Return the node which points to the head of the new LinkedList
Node is defined as
struct node
{
int data;
struct node* next;
node(int x){
data = x;
next = NULL;
}
}*head;
*/
class Solution {
public:
struct node *reverseIt(struct node *head, int k) {
// Complete this method
//dummy Node create karo
node *first = new node(0);
first->next = head;
head = first;
int x;
node *second , *prev , *curr , *front ;
while(first->next)
{
int x = k;
second = first->next;
prev = first;
curr = first->next;
while(x&& curr)
{
front =curr->next;
curr->next = prev;
prev = curr;
curr = front;
x--;
}
first->next = prev;
second->next = curr;
first = second;
}
// Delete dummy node
first = head;
head = head->next;
delete first;
return head;
}
};
//{ Driver Code Starts.
/* Drier program to test above function*/
int main(void) {
int t;
cin >> t;
cin.ignore();
while (t--) {
vector<int> arr;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
if (arr.empty()) {
cout << -1 << endl;
continue;
}
int data = arr[0];
node* head = new node(data);
node* tail = head;
for (int i = 1; i < arr.size(); ++i) {
data = arr[i];
tail->next = new node(data);
tail = tail->next;
}
int k;
cin >> k;
cin.ignore();
Solution ob;
head = ob.reverseIt(head, k);
printList(head);
}
return (0);
}
// } Driver Code Ends