单个圆形链表排序

时间:2017-01-25 14:48:06

标签: algorithm data-structures linked-list circular-list

我正在尝试在每次编辑后对单个循环链表进行排序。但我的代码不起作用。我基于选择排序算法。我已经这样做了好几个小时但似乎无法获得正确的代码。

void editList(node *head, int value, int newValue)
{
    node *traverser = head;
    do {
        traverser = traverser -> next;
    }while(traverser -> data != value);

    traverser -> data = newValue;

    node *index;
    node *selection;
    node *temp = new node;

    for(index = head; index -> next != head; index = index -> next) {

        for(selection = head; selection -> next != head; selection = selection -> next) {
            if(index -> data > selection -> data) {
                temp -> data = index-> data;
                index -> data = selection -> data;
                selection -> data = temp -> data;

            }
        }//End of outer loop

    }//End of sorting

    return;
}//End of editList()

1 个答案:

答案 0 :(得分:1)

在分析提供的源代码时,建议的排序算法非常接近预期的'选择排序算法

存在两个嵌套循环,但是执行独立功能。

第1步 - 通过将条件从第一个循环包含到第二个循环来执行真正的嵌套循环。

  

要对所有列表进行排序,选择将从下一个节点开始   索引。

for(index = head; index -> next != head; index = index -> next) {
    // start the selection from the index->next
    for(selection = index->next; selection -> next != head; selection = selection -> next) {
        if(index -> data > selection -> data) {
            temp -> data = index-> data;
            index -> data = selection -> data;
            selection -> data = temp -> data;

        }
    }//End of outer loop
}//End of sorting

Bonus 1 - 因为交换仅在data级别执行,而不是使用临时节点,只需使用整数。

// use just an integer
int temp;
...
temp = index-> data;
index -> data = selection -> data;
selection -> data = temp;

而不是:

// allocated but never freed
node *temp = new node;
...
temp -> data = index-> data;
index -> data = selection -> data;
selection -> data = temp -> data;

Bonus 2 - 对于第一个搜索部分本地化要替换int value的节点,为什么不使用相同的循环结构来防止永不停止的循环,如果没有节点具有搜索值。

node *traverser;
// a ending loop to search a value into a circular-list
for(traverser = head; traverser->next != head; traverser = traverser -> next) {
    if (traverser -> data == value) {
        traverser -> data = newValue;
        break;
    }
}

而不是

node *traverser = head;
do {
    traverser = traverser -> next;
}while(traverser -> data != value);

traverser -> data = newValue;