Repository navigation
Expand file tree
/
Copy path61.cpp
More file actions
74 lines (69 loc) · 1.74 KB
/
Copy path61.cpp
File metadata and controls
74 lines (69 loc) · 1.74 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteathead(ListNode* head) {
ListNode* temp = head->next;
head->next=NULL;
delete(head);
head=temp;
return head;
}
ListNode* addattail(int val, ListNode* head) {
ListNode* temp=head;
while (temp->next!= NULL) {
temp = temp->next;
}
ListNode* newnode = new ListNode(val);
temp->next=newnode;
return head;
}
ListNode* reverseList(ListNode* head) {
stack<int>st;
ListNode* temp=head;
while(temp){
st.push(temp->val);
temp=temp->next;
}
temp=head;
while(temp){
temp->val=st.top();
st.pop();
temp=temp->next;
}
return head;
}
ListNode* rotateRight(ListNode* head, int k) {
ListNode* temp = head;
if(head==NULL){
return NULL;
}
else if(head->next==NULL){
return head;
}
if (k == 0) {
return head;
}
int c=0;
while (temp->next!= NULL) {
temp = temp->next;
c++;
}
head=reverseList(head);
while ((k%(c+1))!= 0) {
head = addattail(head->val, head);
head = deleteathead(head);
k--;
}
head=reverseList(head);
return head;
}
};