2017-06-18 76 views
2

現在,我正在通過使用C++來介紹算法。 的問題是:無符號長返回指向一個類的指針

解釋瞭如何使用,而不是通常的兩個(next和prev)的每個項目只有一個指針 值x.np實現雙向鏈表。假設 所有的指針值可以被解釋爲k位整數,並且 定義x.np = x.next異或x.prev,x.next的k位「異或」和x.prev。 (值NIL由0表示)。請務必描述 訪問列表頭部所需的信息。顯示如何 在這樣的列表上實現SEARCH,INSERT和DELETE操作。 同時顯示如何在O(1)時間內反轉這樣的列表。

在XOR函數中,我首先將指針轉換爲unsigned long類型的XOR和XOR這兩個值。然後將結果轉換回指向類的指針。我不知道爲什麼它不起作用。這裏是我的代碼:

struct node 
{ 
int key; 

node *np; 
} ; 

struct list_n 
{ 
node *head; 

node *tail; 
}; 

以上是兩個結構及以下插入

void insert_element(list_n *_list, int _key) 
{ 
    node *present_node= new node; 

    present_node->key=_key; 

    present_node->np=xor_gate(nullptr,_list->tail); 

    if(_list->tail) _list-> tail->np=xor_gate(present_node,xor_gate(nullptr,_list->tail->np)); 

    if(!_list->head) _list->head=present_node; 

    _list->tail=present_node; 
} 

下面是異或門:

node *xor_gate(node *left,node *right) 
{ 
    unsigned long result; 

    result = (reinterpret_cast<unsigned long>(left))^(reinterpret_cast<unsigned long>(right)); 

    node *output =new node; 

    output = reinterpret_cast<node*> (result); // yes or no 

    return output ; 
} 


void list_n_inti(list_n *a) 
{ 
    a->head =nullptr; 

    a->tail =nullptr; 
} 

我檢查代碼幾次。我認爲這個問題是由異或門造成的。

如果您發現錯誤,請告訴我。如果您有其他方法可以回答這個問題。請告訴我。

謝謝

+0

的unsigned long類型主要尺寸或可能不匹配指針的大小,有'::性病:: uintptr_t'整數類型,可容納PTR值。你的'xor_gate'中的'output'是用新分配的'node'實例初始化的,但是你立即用另一個值覆蓋它,所以內存泄漏。在C++中,您使用構造函數執行初始化,像'list_n_inti'這樣的函數通常會指示一個臭味代碼... – VTT

+0

'node * output = new node; output = reinterpret_cast (result);'第二個語句覆蓋第一個存儲的值,而'new節點'給出的指針不見了。 –

+0

感謝您的回答。正如你所提到的,我改變了我的代碼。但我仍然有一個錯誤,在這一行 present_node-> np = xor_gate(nullptr,_list-> tail);如果我將第二個輸入更改爲nullptr,則此程序將起作用。我不知道爲什麼會發生。 –

回答

1

有在xor_gate內存泄漏,但我認爲,如果你編譯爲32位代碼工作。如果將其編譯爲64位,則unsigned long通常不能包含指針。

試試這個:

#include <cstdint> // for uintptr_t 

node *xor_gate(node *left,node *right) 
{ 
    using std::uintptr_t; 

    uintptr_t result = (reinterpret_cast<uintptr_t>(left))^(reinterpret_cast<uintptr_t>(right)); 

    return reinterpret_cast<node*> (result); 
}