Leetcode - Reverse Nodes in k-Group

本文详细介绍了链表逆序的几种实现方法,包括递归和迭代的方式,并提供了具体的代码实现示例。通过这些示例,读者可以了解到如何有效地逆序链表的不同部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[分析]
使用递归会Memory Limit Exceed,迭代方式参考
[url]https://leetcode.com/discuss/17483/share-my-java-solution-with-comments-in-line[/url]
解析见代码注释
Reverse Linked List, Reverse Linked List II 可使用此题的解题技巧,可联系着体会,而Reorder List中包含Reverse Linked List步骤。


/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
// prev->head->...->...->tail->|...| //init state of reversing k group [head, tail]
// prev->tmp->...->...->tail->|...|
// prev->...->...->tail->tmp->|...| //delete tmp & insert at tail.next
// prev->...->tail->tmp'->...->head->|...| //keep doing until prev.next = tail
// prev->tail->...->...->head->|...| // finish state
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null || k < 2)
return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy, tail = head, tmp;
while (true) {
// check remain length of list
int count = 0;
while (tail != null) {
count++;
if (count == k) break;
tail = tail.next;
}
if (tail == null) break;
// reverse a K group
head = prev.next;
while (prev.next != tail) {
tmp = prev.next;
prev.next = tmp.next; // delete tmp from prev.next
tmp.next = tail.next; // step 1 of inserting tmp at tail.next
tail.next = tmp; // step 2 of inserting tmp at tail.next
}
prev = head;
tail = head.next;
}
return dummy.next;
}
}


public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode curr = head.next;
head.next = null;
ListNode prev = head, next;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
public ListNode reverseList1(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode tail = head;
while (tail.next != null) {
tail = tail.next;
}
ListNode tmp;
while (dummy.next != tail) {
tmp = dummy.next;
dummy.next = tmp.next;
tmp.next = tail.next;
tail.next = tmp;
}
return tail;
}
}



public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
int count = 1;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy; //prev is the (m-1)th node
while (count < m) {
prev = prev.next;
count++;
}
ListNode tail = prev.next;
while (count < n) { // tail is the nth node
tail = tail.next;
count++;
}
ListNode tmp;
while (prev.next != tail) {
tmp = prev.next;
prev.next = tmp.next;
tmp.next = tail.next;
tail.next = tmp;
}
return dummy.next;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值