使用冒泡排序旋转链接列表

时间:2017-06-14 08:50:54

标签: c linked-list bubble-sort

我试图编写一个函数,用于以这种方式旋转链表:1 - > 2 - > 3 - > 4,如果用户选择要移动的第一个节点,则将3个节点转发为:2-> 3-> 1-> 4-> END(在两个节点之间切换,直到它到达第三个节点,它看起来像冒泡排序)。另一个例子:如果用户选择第一个节点作为第一个节点,它将如下所示:2-> 1> 3-> 4-> END。

2 个答案:

答案 0 :(得分:0)

可能喜欢以下过程。 (未经测试的伪代码)

void rotateLeftOne(Node *np, int rotateLength){
    if(np == NULL || np->next == NULL)
        return;
    assert(rotateLength <= listLength(np));
    for(int i = 1; i < rotateLength && np->next; ++i, np = np->next){
        swap(&np->value, &np->next->value);
    }
}

答案 1 :(得分:0)

以下是必需的代码片段 - 它将执行所需的操作。你可以see the complete working here。代码中的函数void shiftNode(Node** rootNode, int nodeIndex, int shifts)将节点转移到所需的位置:

typedef struct N
{
    int val;
    struct N* next;
}Node;

/** Index starts from 0*/
void shiftNode(Node** rootNode, int nodeIndex, int shifts)
{
    int i=1;
    Node *pNode, *temp, *root = *rootNode;
    if((shifts <= 0) || (nodeIndex < 0))
    {
        return;
    }

    if(nodeIndex != 0)
    {
        for(i=1; i<nodeIndex; i++)
        {
            root = root->next;
        }
        pNode = root->next;
        root->next = pNode->next;
    }
    else
    {
        *rootNode = root->next;
        pNode = root;
        root->next = pNode->next;
    }

    for(i=0; i<shifts; i++)
    {
        root = root->next;
    }
    temp=root->next;
    root->next = pNode;
    pNode->next=temp;
}