在链接列表前n位置中移动某个节点

Moving a certain node in a linked list forward n positions

本文关键字:移动 节点 位置 链接 列表      更新时间:2023-10-16

我正在尝试在链接列表中移动节点向前n位置

例如

列表:1、2、3、4、5、6

移动'2'向前3位置

新列表:1、3、4、5、2、6

这就是我尝试的

void MoveNodeForward(Node* head, int x, int n)
{
    Node* t = head;
    while(t != NULL)
    {
        if(t->data == x)
        {
            for(int i=0; i<n && t->next != NULL; i++)
            {
                int temp = t->next->data;
                t->next->data = t->data;
                t->data = temp;
                t = t->next;
            }
        }
        t = t->next;
    }
}

,但它只是交换节点的值。

我需要一种方法来改变节点本身的位置,而不仅仅是值。

void move_n_position(struct node **p1,int position,int n)//n is the no of time moving front
{
int i;
struct node *bef=NULL;
struct node *prev=NULL;
struct node *temp=*p1;
for(i=1;i<position;i++)
{
    prev=temp;
temp=temp->link;

}
if(prev!=NULL)
{
bef=temp;
prev->link=bef->link;
}
else
{
    bef=temp;
    (*p1)=(*p1)->link;
}
i=0;
while(i<n)
{
 temp=temp->link;
 i++;
}
bef->link=temp->link;
temp->link= bef;
}