C++ 双链表的反向函数
如果我在列表中发送反向函数,我会得到预期的输出。但是如果我使用reverseNth函数,我只会得到列表中的第一项。ReverseNth在节中反转列表。 例如,如果我有一个列表=。调用reverse将输出。在列表上调用reverseNth2应该会给出一个错误 相关代码:C++ 双链表的反向函数,c++,linked-list,doubly-linked-list,C++,Linked List,Doubly Linked List,如果我在列表中发送反向函数,我会得到预期的输出。但是如果我使用reverseNth函数,我只会得到列表中的第一项。ReverseNth在节中反转列表。 例如,如果我有一个列表=。调用reverse将输出。在列表上调用reverseNth2应该会给出一个错误 相关代码: void List<T>::reverse( ListNode * & startPoint, ListNode * & endPoint ) { if(startPoint == NULL |
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;
}
}
反向代码:
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;
}
您没有在反向函数中使用startPoint和endPoint。目前,您的reverse函数反转整个列表,将旧的head->next to point保留为null,因为它现在是结束
我猜reverse函数用于反转整个列表,但后来被扩展为使用任意的开始/结束点,可能是过载?我更改了我的反转,因此我引用的不是头和尾,而是起始点和结束点。现在我又犯了一个错误?我将代码编辑为我所拥有的。好吧,首先,你的p实际上是指向末尾的。呜呜=NULL仍将进入列表的末尾。因此,我更改了while循环,使其正确。但我不明白你说的p问题是什么意思?