本文已参与「新人创作礼」活动,一起开启掘金创作之路。
C++ 循环出队问题
源代码
struct ListNode
{
ListNode* next;
int val;
};
//循环出队,size表示当前的总数据,比如13(1,2,3,...,13)
//startIndex表示从起始位置
//k表示从哪个数开始出队
//例如:13,4,1
//则出对列表:4 5 6 7 8 9 10 11 12 13 1 2 3
void PushQueue(int size, int startIndex, int k)
{
ListNode* pStart = nullptr, * pEnd = nullptr, * curEnd = nullptr;
int count = 0;
while (count++ < size)
{
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->next = nullptr;
node->val = count;
if (count == 1)
{
pStart = node;
pEnd = pStart;
}
else
{
if (count == size)
curEnd = node;
pEnd->next = node;
pEnd = node;
}
pEnd->next = pStart;
}
pEnd = curEnd;
curEnd = nullptr;
count = 0;
int index = 0;
while (index++ < size)
{
while (count < startIndex)
{
if (++count == startIndex)
break;
pStart = pStart->next;
pEnd = pEnd->next;
}
ListNode* temp = pStart;
if (k == 1)
{
pEnd->next = pStart->next;
pStart = pStart->next;
cout << temp->val << " ";
free(temp);
}
else
{
int tempCount = 0;
while (tempCount < k)
{
if (++tempCount == k - 1)
break;
temp = temp->next;
}
ListNode* tempNode = temp->next;
cout << temp->next->val << " ";
temp->next = temp->next->next;
if (tempNode == pStart)
pStart = tempNode->next;
free(tempNode);
}
}
}
int main()
{
PushQueue(13, 4, 1);
return 0;
}
版权声明:本文为CSDN博主「ufgnix0802」的原创文章:
原文链接:(blog.csdn.net/qq135595696…)