[英]reverse part of a doubly linked list
我正在嘗試實現自己的列表類,但是在反轉列表的一部分時遇到了麻煩。
相關代碼:
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
剩下的列表丟失了(嗯,仍然可以從我的全局tail變量訪問)。 有任何想法嗎? 我的方法錯了嗎?
如果反轉段[first,last],則需要將first->next
設置為last->next
,而不要像代碼一樣將first->next
設置為first->prev
。
一個更簡單的解決方案。
/**
* 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;
}
該問題發生在第一個節點上,因為節點1的上一個指針為NULL,並且您將其分配給節點1的下一個指針。 您應該在節點5旁邊分配1。
您的head->prev
必須在first for loop中指向NULL
。 您最好以外交方式進行思考和實施,這將有所幫助。 您需要t->next->next =t->next
。
在方法參數中,將“指針”與“參考”混合在一起。
void List::reverse(ListNode * & head, ListNode * & tail)
也許你的意思是?
void List::reverse(ListNode* head, ListNode* tail)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.