如何在链表中将节点从头移动到尾? C

how to move nodes from begining to the end in linked list? C

我想构建一个程序,从 linked 列表的开头获取 K 个元素并将它们放在 linked link 的末尾,有点旋转。 例如:如果有 linked 列表:1->2->3->4->5 并且 k = 2 那么 linked 列表将如下所示:3->4->5->1->2 这是我的尝试,请帮助我:

void spinfunc(struct node *node_ptr)
{
    int k = 0;
    int count = 0;
    int temp;
    printf("enter a number of the lements from the begin to be deleted - ");
    scanf("%d", &k);
    while (node_ptr != NULL)
    {
        if (count + 1 <= k)
        {
            count++;
            printf("count: %d", count);
            temp = node_ptr->data;
            node_ptr->data = NULL;
        }
        node_ptr = node_ptr->next;
    }
    printf("%d ", temp);

}

可以通过更简单的步骤完成。

我们只需要改变链表的第k个节点和尾节点的下一个指针即

kth node -> next = null
tail node -> next = head

然后更新头部到第(k+1)个节点。

整体逻辑:

从头开始遍历链表,在第k个节点处停止。存储指向第 k 个节点的指针。我们可以使用 kthNode->next 获得第 (k+1) 个节点。继续遍历直到结束并将指针也存储到最后一个节点。最后,如上所述更改指针。

struct node* spinFunc(struct node *head)

{

int k = 2; //assuming k = 2 
// list = 1->2->3->4->5.
struct node* current = head;
struct node* newHead = NULL;

int count = 1;
while (count < k && current != NULL)
{
    current = current->next;
    count++;
}
//Now current is pointing to node 2 

// current points to kth node. Store it in a variable.
struct node *kthNode = current;

// current will point to last node i.e. node 5 after this loop
while (current->next != NULL)
    current = current->next;

//last node -> next = head
current->next = head;

//update the head now
newHead = kthNode -> next;

kthNode->next = NULL;

//return the new head
return newHead;

}

我个人喜欢采用循环链表来解决这类问题。不要将链接列表中的最后一个节点指向 Null,而是将其指向列表中的第一个节点。这种类型列表的另一个技巧是保留对最后一个节点的引用,而不是第一个。您的问题现在只需通过正确的节点数更改对列表的引用即可解决。

循环链表的其他优点是追加到开头或结尾现在变得微不足道,这个优点不会使列表中的其他操作变得更难。