gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:54:03 25 4
gpt4 key购买 nike

我想构建一个程序,从链表的开头获取 K 个元素并将它们放在链接的末尾,有点自旋。例如:如果有链表:1->2->3->4->5并且 k = 2 那么链表将如下所示: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个节点和尾节点的next指针即

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;

关于c - 如何在链表中将节点从头移动到尾? C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37747488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com