我必须将 LL 的最后 n 个元素附加到前面

I have to append last n element of LL to front

本文关键字:元素 前面 最后 LL      更新时间:2023-10-16
node* append_LinkedList(node* head,int n)
{
//write your code here
int count=0;
node *temp=head;
while(count<n-1)
{
temp=temp->next;
count++;
}
cout<<temp->data;
return head;
}

下一步我无法思考。获得第 n 个节点指针后下一步该怎么做。

绝对看起来像是一个家庭作业问题。

考虑以下术语: 考虑以下链表,您希望将节点 C 移到前面。

A -> B -> C -> D -> E

将当前head指针存储在变量中。遍历链表,直到找到C。将C的上一个节点标记为null。将head存储在C处并循环,直到到达列表的末尾,在本例中为E。现在,将Enext指向最初存储的head

所以你的输出将是C -> D -> E -> A -> B

Move last n element to front of a given Linked List. I am not getting correct  output
node* append_LinkedList(node* head,int n)
{
//write your code here
int size=0;
node *temp2=head;
while(temp2->next!=NULL)
{
temp2=temp2->next;
size++;
}
int count=0;
node *temp=head;
node *head3=temp;
while(count<size-n-1)
{
temp=temp->next;
count++;
}
head=temp->next;
temp->next=NULL;
temp2->next=head3;
return head;
}