先给出一个写的比较差的版本:
#include <iostream>
struct node
{
int data;
node* next;
node(int eData, node* eNext)
{
data = eData;
next = eNext;
}
};
void processLL(node** head, int m, int n)
{
if(!head)
return;
node* cur = *head;
int cntM = 1;
int cntN = 1;
node* prev = NULL;
bool isM = true;
while(cur)
{
if(isM)
{
if(cntM == 1 && prev)
{
prev->next = cur;
}
if(cntM == m)
{
prev = cur;
isM = false;
cntM = 1;
}
else
cntM++;
cur = cur->next;
}
else
{
if(cntN == n)
{
isM = true;
cntN = 1;
}
else
cntN++;
node* tmp = cur;
cur = cur->next;
delete tmp;
if(!cur && prev)
{
prev->next = NULL;
break;
}
}
}
};
void init(node** head, int n)
{
node* cur = NULL;
for(int i = 1; i <= n; i++)
{
if(!*head)
{
*head = new node(i, NULL);
cur = *head;
}
else
{
cur->next = new node(i, NULL);
cur = cur->next;
}
}
};
int main()
{
node* head;
head = NULL;
init(&head, 10);
processLL(&head, 2, 3);
return 0;
}
下面是一个精简后的版本 这道问题不难 主要是要考虑全面 代码清晰
#include <iostream>
struct node
{
int data;
node* next;
node(int eData, node* eNext)
{
data = eData;
next = eNext;
}
};
void processLL(node** head, int m, int n)
{
if(!head)
return;
node* cur = *head;
int cnt = 1;
node* prev = NULL;
while(true)
{
cnt = 1;
while(cnt <= m)
{
if(cnt == 1 && prev)
prev->next = cur;
if(cnt == m)
prev = cur;
cnt++;
cur = cur->next;
if(!cur)
return;
}
cnt = 1;
while(cnt <= n)
{
cnt++;
node* tmp = cur;
cur = cur->next;
delete tmp;
if(!cur && prev)
{
prev->next = NULL;
return;
}
}
}
};
void init(node** head, int n)
{
node* cur = NULL;
for(int i = 1; i <= n; i++)
{
if(!*head)
{
*head = new node(i, NULL);
cur = *head;
}
else
{
cur->next = new node(i, NULL);
cur = cur->next;
}
}
};
int main()
{
node* head;
head = NULL;
init(&head, 10);
processLL(&head, 1, 3);
return 0;
}