给你一个链表的头节点 head
,旋转链表,将链表每个节点向右移动 k
个位置。
思路一:模拟题意
struct ListNode* rotateRight(struct ListNode* head, int k){
if(head==NULL)return NULL;
struct ListNode* p = head,*pre=head,*new_head=NULL;
int num = 1;
while(p!=NULL&&p->next!=NULL)
{
p=p->next;
num++;
}
if(p!=NULL)
p->next=head;
for(int i=0; pre!=NULL&&i<num-k%num-1;i++)
{
pre=pre->next;
}
new_head=pre->next;
pre->next=NULL;
return new_head;
}
分析:
本题将链表每个节点向右移动k个位置,即p=p->next次。再将下一个节点重新赋到起点上,再不断向后排,最后返回新链表。
总结:
本题考察对链表的应用,将链表节点掌握好则可解决。