Обратная функция для двусвязного списка

Если я отправлю свою функцию реверса в список, я получу ожидаемый результат. Но если я использую свою функцию reverseNth, я получу только первое, что есть в моем списке. ReverseNth переворачивает список в разделах.
Например, если у меня есть список = <1 2 3 4 5>. Вызов reverse () выведет <5 4 3 2 1>. Вызов reverseNth (2) в списке должен дать <2 1 4 3 5>.

Соответствующий код:

void List<T>::reverse( ListNode * & startPoint, ListNode * & endPoint )
{
if(startPoint == NULL || startPoint == endPoint)
return;
ListNode* stop = endPoint;
ListNode* temp = startPoint;
startPoint = endPoint;
endPoint = temp;
ListNode* p = startPoint; //create a node and point to head

while(p != stop)
{
temp = p->next;
p->next = p->prev;
p->prev = temp;
p = p->next;
}
}

ReverseNth код:

void List<T>::reverseNth( int n )
{
if(head == NULL || head == tail || n == 1 || n == 0)
return;

if(n >= length)
{
reverse(head,tail);
return;
}

ListNode* tempStart = head;
ListNode* tempEnd;

for(int j = 0; j < length; j += n)
{
// make the end of the section the beginning of the next
tempEnd = tempStart;
// set the end of the section to reverse
for(int i = 0; i < n-1; i ++)
{
// check to make sure that the section doesn't go past the length
if(j+i == length)
i = n;
else
tempEnd = tempEnd-> next;
}

reverse(tempStart, tempEnd);

if( j == 0)
head = tempStart;
if(tempStart == tail)
{
tail = tempEnd;
return;
}
else
tempStart = tempEnd-> next;
}
tail = tempEnd;
}

1

Решение

Вы не используете startPoint а также endPoint в вашей обратной функции. В настоящее время ваша обратная функция переворачивает весь список, оставляя старый head->next указать на ноль (так как теперь это конец).

Я предполагаю, что функция реверса использовалась для реверса всего списка, но затем была расширена, чтобы принять произвольную начальную / конечную точку (возможно, перегрузку?).

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector