我有一個函數需要一個雙向鏈表。頭是第一個節點,尾是最後一個節點。有52個節點(卡牌)我試圖做的是執行一個洗牌,就像你用手洗牌一樣。所以你把甲板砍下一半,從上半部分拿下底牌,將底牌從另一半上取下,並將其放在頂部。將一個鏈表重新排序
所以。左半部分是1 2 3右半部分是4 5 6後洗牌4 1 5 2 6 3
我知道我的錯誤是在指針中,他們相互覆蓋。我只是不知道如何正確地對這些列表進行排序,並將它們一個接一個地抽出來,然後將它們粘在一起。
bool Shuffle(deck* &head, deck* &tail, int ShuffleAmnt)
{
deck* temp_tail = nullptr;
deck* temp_head = head;
deck* temp_list = new deck;
for (int i = 1; i < 26; i++)
temp_head = temp_head->next;
temp_tail = temp_head->next;
temp_tail->previous = nullptr;
temp_head->next = nullptr;
while (head->next != NULL) // get to the bottom of head
head = head->next;
temp_head->previous = nullptr;
temp_tail->next = nullptr;
for (int i = 1; i < 26; i++)
{
temp_list->next = temp_head;
temp_head = head->previous;
temp_list = temp_list->next;
temp_list->next = temp_tail;
}
head = temp_list;
return(true);
}
你的第三個參數是做什麼的? – TheDillo 2014-12-13 08:09:40
這是誰的想法來代表一個鏈接列表卡組?一個'std :: vector','std :: array'或者一個普通的舊數組更有意義。 – PaulMcKenzie 2014-12-13 08:17:09
洗牌鏈接列表的最安全方法是將數據複製到數組,將數組隨機混洗,然後將數組結果複製回您的列表。假設你有通過你的列表的函數,並且可以將數據複製回你的列表。此外,洗牌應該是隨機的,而不是像你的代碼似乎暗示的那樣「控制」。例如:在洗牌後,甲板上的第一張牌可能會潛在甲板上的任何位置。 – PaulMcKenzie 2014-12-13 08:23:00