我正在尝试实现自己的列表类,但是我无法撤消列表中的部分内容。
Revelant code:
void List<T>::reverse(ListNode * & head, ListNode * & tail)
{
ListNode* t;
ListNode* curr = head;
ListNode * funtail = tail;
int stop=0;
while(stop==0)
{
if(curr==funtail)
{
stop = 1;
}
t = curr->prev;
curr->prev = curr->next;
curr->next = t;
curr = curr->prev;
}
t = tail;
tail = head;
head = t;
}
如果我从列表开始
1 2 3 4 5 6 7 8 9 10
我将指针传递给1和4,然后列表应该看起来像
4 3 2 1 5 6 7 8 9 10
问题是,我的列表只返回
1
列表的其余部分丢失(好吧,仍然可以从我的全局尾部变量访问)。有任何想法吗?我的方法不对吗?
答案 0 :(得分:2)
如果您反向细分[first,last],则希望first->next
设置为last->next
,而不是first->prev
,就像您的代码一样。
答案 1 :(得分:0)
第一个节点出现问题,因为节点1的前缀指针为NULL,并且您将其分配给节点1的下一个节点。您应该在节点5旁边分配1
答案 2 :(得分:0)
您的head->prev
必须首先指向NULL
for循环。你最好以思维方式思考和实施它会有所帮助。您需要t->next->next =t->next
。
答案 3 :(得分:0)
更简单的解决方案。
/**
* Traverses half of the list and swaps a node with another node(
here by termed as the reflection node)
* which lies at a position = listSize - (i +1) for every i.
* Reassignment of element is not needed, hence a soul saver from
* the copy constructor thing ( '=' assignment operator stuff).
*/
template <typename E> void DLinkedList<E>::reverse(){
int median = 0;
int listSize = size();
int counter = 0;
if(listSize == 1)
return;
/**
* A temporary node for swapping a node and its reflection node
*/
DNode<E>* tempNode = new DNode<E>();
for(int i = 0; i < listSize/2 ; i++){
DNode<E>* curNode = nodeAtPos(i);
// A node at 'i'th position
DNode<E>* reflectionNode = nodeAtPos(listSize - (i + 1));
// Reflection of a node considering the same distance from the median
/**
* swap the connections from previous and next nodes for current and
* reflection nodes
*/
curNode->prev->next = curNode->next->prev = reflectionNode;
reflectionNode->prev->next = reflectionNode->next->prev = curNode;
/**
* swapping of the nodes
*/
tempNode->prev = curNode->prev;
tempNode->next = curNode->next;
curNode->next = reflectionNode->next;
curNode->prev = reflectionNode->prev;
reflectionNode->prev = tempNode->prev;
reflectionNode->next = tempNode->next;
}
delete tempNode;
}
template <typename E> int DLinkedList<E>::size(){
int count = 0;
DNode<E>* iterator = head;
while(iterator->next != tail){
count++;
iterator = iterator->next;
}
return count;
}
template <typename E> DNode<E>* DLinkedList<E>::nodeAtPos(int pos){
DNode<E>* iterator = head->next;
int listSize = size();
int counter = 0;
while(counter < pos){
iterator = iterator->next;
counter++;
}
return iterator;
}
答案 4 :(得分:-1)
在方法参数中,您将“指针”与“参考”混合。
void List::reverse(ListNode * & head, ListNode * & tail)
也许你的意思?
void List::reverse(ListNode* head, ListNode* tail)