Reverse
My Solutions:
Time: O(n); Space: O(1)
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode pre = null;
while (head != null) {
ListNode temp = head.next; // store next
head.next = pre; // reverse current(head) node's pointer
pre = head; // move pointers one position ahead
head = temp;
}
return pre;
}
recursive version
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.
My Solutions:
只反转从m到n位置的nodes,所以需要先走到m之前的位置,然后反转到n-m的位置
Time: O(n); Space: O(1)
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null || m > n) return null;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
//find the node right before the reversed one
for (int i = 0; i < m - 1; i++) pre = pre.next;
ListNode first = pre.next;
ListNode second = first.next;
for (int i = 0; i < n - m; i++) {
first.next = second.next;
second.next = pre.next;
pre.next = second;
second = first.next;
}
return dummy.next;
}
}
25。Reverse Nodes in k-Group
Given the head
of a linked list, reverse the nodes of the list k
at a time, and return the modified list.
k
is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k
then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Example 2:
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
My Solutions:
这道题和#92是类似的。
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || k == 1) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode curr = dummy;
int count = 0; // count of nodes in the list
while (curr.next != null) {
curr = curr.next;
count++;
}
// dummy --> 1 --> 2 --> 3 --> 4
// pre curr next
// dummy --> 2 --> 1 --> 3 --> 4
// pre curr next
// dummy --> 3 --> 2 --> 1 --> 4
// pre next curr
// pre curr next
// dummy --> 3 --> 2 --> 1 --> 4 --> 5
// pre
// curr
// next
ListNode pre = dummy, next = dummy;
// do the reverse unless there're not enough nodes
while (count >= k) {
curr = pre.next; // curr is 1
next = curr.next; // next is 2
for (int i = 1; i < k; i++) {
curr.next = next.next; // connect 1 to 3 // connect 1 to 4
next.next = pre.next; // connect 2 to 1 // connect 3 to 2
pre.next = next; // connect dummy to 2 // connect dummy to 3
next = curr.next; // put next pointer to 1 // put next pointer to 1
}
pre = curr;
count -= k;
}
return dummy.next;
}
Last updated