Linked list Flip
Give a list and a number of k, such as linked list 1→2→3→4→5→6
If k=2, flip after 2→1→4→3→6→5,
If k=3, flip after 3→2→1→6→5→4,
If k=4, flip after 4→3→2→1→5→6,
Using the program to achieve node* rotatelist (node* list, size_t K).
My idea is that every K-node inverse of the linked list as a new linked list, so a total of m=size/k bar, and then use the last linked list of the tail tail and the current list of the head newlist connection. So to save the tail of each list, but we know this is the inverse of the list, so the part that has not been reversed is the end of the list, which is the head in the code. Finally, the remaining chain chains are on the tail of the new list.
Counter-linked list K
plist* rotatelist (plist* pplist, size_t k)
{
assert (*pplist);
int m = Size (*pplist)/k; Calculates the number of new linked lists
if (M <= 0 && k==1)
{return
NULL;
}
Pnode cur = *pplist;
Pnode tail = cur; Save the end node of the current list
plist* head = pplist; Returns a value that holds the first node of the entire list for
(int i = 0; i < m; i++)//loop inverse M-list
{
plist newlist = NULL; Each k node is treated as a new linked list
pnode head = cur; The head of the current list, that is, the tail node of the following list
int k = k;
while (K > 0) //k the inverse of a node
{
pnode tmp = cur;
cur = cur->next;
Tmp->next = NewList;
NewList = tmp;
k--;
}
if (i = = 0) //The first inverse of the new linked list to do the entire list of the head
{
*head = newlist;
}
else //The end of the last linked list and the new chain links
{
tail->next = newlist;
tail = head; Update the tail of the linked list
}
while (cur) ///link the remaining K-less nodes to the tail of the linked list (
{
tail->next = cur;
tail = tail->next;
cur = cur->next;
}
return head;
}
Test: Multiple inversion of a linked list
void Testlist ()
{
plist l1 = NULL;
Pushback (&L1, 1);
Pushback (&L1, 2);
Pushback (&L1, 3);
Pushback (&L1, 4);
Pushback (&L1, 5);
Pushback (&L1, 6);
Pushback (&L1, 7);
Pushback (&L1, 8);
Pushback (&L1, 9);
Pushback (&L1);
Print (L1);
cout << Endl;
plist* Ret1 = Rotatelist (&L1, 1);
Print (*RET1);
plist* Ret2 = Rotatelist (&L1, 2);
Print (*ret2);
plist* Ret3 = Rotatelist (&L1, 3);
Print (*RET3);
plist* Ret4 = Rotatelist (&L1, 6);
Print (*RET4);
}