-
Notifications
You must be signed in to change notification settings - Fork 2
/
ReverseLinkedList.java
39 lines (32 loc) · 979 Bytes
/
ReverseLinkedList.java
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
package leetcode.list;
import leetcode.helpers.ListNode;
public class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
ListNode current = head;
ListNode previous = null;
while (current != null) {
ListNode next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummyHead = new ListNode(-1);
ListNode pre = dummyHead;
pre.next = head;
for (int i = 0; i < m - 1; i++) {
pre = pre.next;
}
ListNode current = pre.next;
ListNode next = current.next;
for (int i = 0; i < n - m; i++) {
current.next = next.next;
next.next = pre.next;
pre.next = next;
next = current.next;
}
return dummyHead.next;
}
}