-
Notifications
You must be signed in to change notification settings - Fork 297
/
Linklist.cpp
97 lines (73 loc) · 1.66 KB
/
Linklist.cpp
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
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
};
// This function rotates a linked list
// counter-clockwise and updates the
// head. The function assumes that k is
// smaller than size of linked list.
// It doesn't modify the list if
// k is greater than or equal to size
void rotate(Node** head_ref, int k)
{
if (k == 0)
return;
list = 10->20->30->40->50->60.
Node* current = *head_ref;
int count = 1;
while (count < k && current != NULL) {
current = current->next;
count++;
}
if (current == NULL)
return;
Node* kthNode = current;
while (current->next != NULL)
current = current->next;
current->next = *head_ref;
// Change head to (k+1)th node
// head is now changed to node 50
*head_ref = kthNode->next;
// change next of kth node to NULL
// next of 40 is now NULL
kthNode->next = NULL;
}
/* UTILITY FUNCTIONS */
/* Function to push a node */
void push(Node** head_ref, int new_data)
{
/* allocate node */
Node* new_node = new Node();
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print linked list */
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
/* Driver code*/
int main(void)
{
/* Start with the empty list */
Node* head = NULL;
// create a list 10->20->30->40->50->60
for (int i = 60; i > 0; i -= 10)
push(&head, i);
cout << "Given linked list \n";
printList(head);
rotate(&head, 4);
cout << "\nRotated Linked list \n";
printList(head);
return (0);
}