Niuke.com High-Frequency Algorithm Questions Series - BM2 - Reversal of Specified Intervals in Linked Lists
Topic description
Inverting the interval from position m to position n in a linked list of size size requires time complexity O(n) and space complexity O(1).
See the original title: Inversion of the specified range in the BM2 linked list
Solution 1: linked list traversal, pointer exchange
Because the starting position may be the head node, first set up a virtual head node dummyNode and point next to the original head node, and then the processing process is as follows:
- First traverse the linked list to find the previous node pre at the starting position m, which is used to record the node before the reversal;
- Then use cur and next to record the next node of pre, and use next to record the next node of cur;
- Then continue to traverse the linked list, transfer the next node to the next node of the pre node by exchanging the next pointers of pre, next, and cur, and then process the next node of cur in a loop;
- Traversing to the node at the end position n is the end of the inversion.
- Finally, the next node that returns the dummyNode node is the reversed linked list.
public class Bm002 {
/**
* @param head ListNode类
* @param m 起始位置
* @param n 结束位置
* @return ListNode类
*/
public static ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null || head.next == null) {
return head;
}
if (m == n) {
return head;
}
// 设置虚拟头结点
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
// pre为反转区间的前一个结点
ListNode pre = dummyNode;
for (int i = 0; i < m - 1; i++) {
pre = pre.next;
}
// cur初始为反转区间的起始结点
ListNode cur = pre.next;
ListNode next;
for (int i = 0; i < n - m; i++) {
// 通过交换next指针指向,将next结点转到pre结点的下一个结点处
next = cur.next;
cur.next = next.next;
next.next = pre.next;
pre.next = next;
}
// 最后,返回dummyNode结点的next结点即为反转后的链表
return dummyNode.next;
}
public static void main(String[] args) {
ListNode head = ListNode.testCase2();
System.out.println("指定区间反转之前");
ListNode.print(head);
ListNode newHead = reverseBetween(head, 2, 4);
System.out.println("指定区间反转之后");
ListNode.print(newHead);
}
}
$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
Believe in the power of persistence!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。