// From curr reverse to end, return reversed linked list head.
ListNode *unguarded_reverse(ListNode *prev, ListNode *curr, ListNode *end)
{
ListNode *next = NULL;
while (curr != end)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
// Reverse linked list from m to n, return head.
// For example:
// Given 1->2->3->4->5->NULL, m = 2 and n = 4,
// return 1->4->3->2->5->NULL.
ListNode *reverse_between(ListNode *head, int m, int n)
{
if (head == NULL || m <= 0 || n <= 0)
{
return NULL;
}
if (m >= n) return head;
ListNode **backup = &head, *p = head, *q = head;
// Move p to the mth node, q to the nth node.
while (p != NULL && --m) backup = &p->next, p = p->next;
while (q != NULL && --n) q = q->next;
// If move success.
if (m == 0 && n == 0 && p != NULL && q != NULL)
{
*backup = unguarded_reverse(q->next, p, q->next);
}
return head;
}
// Reverse every k group in linked list, return head.
// For example,
// Given this linked list: 1->2->3->4->5
// For k = 2, you should return: 2->1->4->3->5
// For k = 3, you should return: 3->2->1->4->5
ListNode *reverse_k_group(ListNode *head, int k) {
if (head == NULL || k < 0) return NULL;
int count = 0;
// Count all node num.
for (ListNode *p = head; p != NULL; p = p->next)
{
++count;
}
for (int i = 1; i + k - 1 <= count; i += k)
{
head = reverse_between(head, i, i + k - 1);
}
return head;
}
链表反转的几种形式
最新推荐文章于 2023-12-03 18:23:51 发布