我有問題,相當多的與此相關的,我問前一陣子插入到排序的位置鏈表
place a value in the sorted position immediately
我不知道你是否能在使用同樣的方法,你在一個鏈表退步找到它應該插入的位置。
如果可能的話你怎麼循環鏈表落後?我無法弄清楚,因爲它似乎不可能,因爲它應該是一個雙鏈接列出,如果我沒有錯,然後呢?無論如何,我正在與單鏈表。
編輯
我想我會爲期待的做法,這是我迄今所取得。我堅持在這一點上我應該如何保存以前的(鍵,值)。這是迄今所做的代碼。 for循環用於查找我想要插入的位置。而且我向前看,如果它達到目的就會破裂。
OK,到目前爲止,現在我想插入值到正確的位置。它在這裏我卡住了。應該怎麼做?現在,當我插入鑰匙:2, 1, 0, 3
,它只會打印出1, 3
struct my_list
{
/* a pointer to the first element of the list */
struct list_link* first;
};
struct list_link
{
int key; // identifies the data
double value; // the data stored
struct list_link* next; // a pointer to the next data
};
struct list_link* create(int key, double value, struct list_link* next)
{
// creates the node;
struct list_link * new_link;
new_link = new struct list_link;
// add values to the node;
new_link->key = key;
new_link->value = value;
new_link->next = next;
return new_link; // Replace this, it is just to be able to compile this file
}
void list_insert(struct my_list* my_this, int key, double value)
{
if(my_this->first == NULL) // add if list empty
my_this->first = create(key, value, my_this->first);
else
{
struct my_list* curr;
struct my_list* prev;
struct my_list start;
start.first = my_this->first;
curr = my_this;
cout << "Too be appended: ";
cout << key << " " << value << endl;
for(curr->first = my_this->first;
key > curr->first->key;
curr->first = curr->first->next)
{
if(curr->first->next == NULL) //peek at front if empty
break;
}
cout << "append here " << key << " > " <<
curr->first->key << endl << endl;
//perform some surgery
if(curr->first->next == NULL)
{
curr->first->next = create(key, value, my_this->first->next);
}
else
{
curr->first = start.first; //move back to start of list
my_this->first = create(key, value, my_this->first);
}
}
}
這是一種創建臨時反向鏈接的方法。 – 2010-10-26 22:38:59