【发布时间】:2010-10-23 17:46:25
【问题描述】:
我的问题与我不久前问的这个问题非常相关
place a value in the sorted position immediately
我想知道您是否可以使用相同的方法,即您在链表中后退以找到应该插入的位置。
如果可能的话,如何向后循环链表?我无法弄清楚,因为它似乎不可能,因为它应该是一个双链接列表,那么如果我没记错的话?无论如何,我正在使用单链表。
编辑
我想我会采用前瞻性方法,这就是我目前所做的。我被困在我应该如何保存前一个(键,值)的问题上。这是到目前为止所做的代码。 for 循环用于查找我要插入的位置。而且我已经向前看,它会在它到达尽头时打破。
到目前为止,好的,现在我想将值插入到正确的位置。在这里我被困住了。应该怎么做?现在当我插入键: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);
}
}
}
【问题讨论】:
标签: c++ linked-list sorted