-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathRotateList.java
More file actions
117 lines (87 loc) · 2.39 KB
/
RotateList.java
File metadata and controls
117 lines (87 loc) · 2.39 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
// @saorav21994
// TC : O(n)
// SC : O(1)
// Note : The initial traversal for count can be omitted if it is guranteed that (k <= n) -> Move to kth node and then start 2 pointer traversal (1 at head and other at kth.next
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
int len = 0;
ListNode tmp = head;
ListNode prev = tmp;
while (tmp != null) {
len += 1;
tmp = tmp.next;
}
if (k != 0 && len != 0) {
k = k % len;
}
if (k == 0 || len == 0) {
return head;
}
k = len - k;
tmp = head;
for (int i = 1; i <= k; i++) {
prev = tmp;
tmp = tmp.next;
}
ListNode start = tmp;
while (tmp.next != null) {
tmp = tmp.next;
}
tmp.next = head;
prev.next = null;
return start;
}
}
// Author : @romitdutta10
// TC : O(N)
// SC: O(1)
// Problem :https://leetcode.com/problems/rotate-list/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null || head.next == null || k <= 0) {
return head;
}
int length = 0;
ListNode temp = head;
ListNode prev = null;
while(temp != null) {
prev = temp;
length++;
temp = temp.next;
}
k = k % length;
if(k == 0) {
return head;
}
prev.next = head;
temp = head;
k = length - k;
while(k-- > 0) {
prev = temp;
temp = temp.next;
}
prev.next = null;
head = temp;
return head;
}
}