LeetCode 61. 旋转链表

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。

示例 1:

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]

示例 2:

输入:head = [0,1,2], k = 4
输出:[2,0,1]

提示:

  • 链表中节点的数目在范围 [0, 500] 内
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 10^9

思路:把链表拆开成两部分,再拼接

用双指针同时移动确定拆开位置

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
 int getlength(struct ListNode *head){
    int n=0;
    while(head){
        n++;
        head=head->next;
    }return n;
 }
struct ListNode* rotateRight(struct ListNode* head, int k) {
    if(head==NULL) return head;
    int n=getlength(head);
    k%=n;
    if(k==0) return head;
    struct ListNode *p=head,*q=head;//开始确定位置
    for(int i=0;i<=k;i++) p=p->next;
    while(p) p=p->next,q=q->next;//p指向空的时候,q指向的位置就是分开的位置
    p=q->next;
    q->next=NULL;
    q=p;
    while(q->next!=NULL)q=q->next;
    q->next=head;
    return p;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值