反转链表
反转链表是一个常见的面试题,现在出现了N多种的变形,各种增加难度。今天看到了一个从m反转到n的,于是手写代码试了试。发现要想把所有情况覆盖全达到bug free还是挺难的。于是,根据各种反转链表题总结了一些比较简练的代码。比较:接口限定的反转链表。
// 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;
}