-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_sublist_of_linked_list.cpp
More file actions
115 lines (101 loc) · 2.25 KB
/
Copy pathreverse_sublist_of_linked_list.cpp
File metadata and controls
115 lines (101 loc) · 2.25 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
//reverse sublist of list
//https://ide.geeksforgeeks.org/nkEw2JhDbC
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node* next;
};
struct Node* createNode(int data){
struct Node* tmp = new Node;
tmp->data = data;
tmp->next = NULL;
return tmp;
}
void printLL(struct Node* head){
if(head == NULL) return;
while(head != NULL){
cout<<head->data<<"\t";
head = head->next;
}
cout<<"\n";
}
void insertAtBegin(struct Node* head, int data){
struct Node* newNode = createNode(data);
if(head == NULL){
newNode->next = NULL;
head = newNode;
return;
}
else{
newNode->next = head;
head = newNode;
return;
}
}
struct Node* reverseList(struct Node* head) {
if(head == NULL) return NULL;
struct Node *curr = head;
struct Node *prev = NULL;
struct Node *next;
while(curr){
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
//head = prev;
return prev;
}
struct Node* reverseSubList(struct Node* head, int m, int n){
struct Node* start = NULL;
struct Node* prev_start = NULL;
struct Node* end = NULL;
struct Node* next_end = NULL;
struct Node* current = head;
int i = 1;
if(m == n)return head;
while(current && i <= n){
if(i < m)prev_start = current;
if(i == m){
start = current;
}
if(i == n){
end = current;
next_end = current->next;
}
current = current->next;
i++;
}
end->next = NULL;
end = reverseList(start);
if(prev_start){
prev_start->next = end;
}
else{
head = end;
}
start->next = next_end;
return head;
}
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main()
{
struct Node* head = NULL;
push(&head, 70);
push(&head, 60);
push(&head, 50);
push(&head, 40);
push(&head, 30);
push(&head, 20);
push(&head, 10);
reverseSubList(head, 3, 6);
printLL(head);
return 0;
}