Leetcode——61. Rotate List

9 篇文章 0 订阅
5 篇文章 0 订阅

题目

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

解答

One Solution:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(head==NULL) return NULL;
        ListNode *p1=head,*p2=head,*res=head,*callen=head;
        if(k==0) return head;
        int len=0;
        while(callen!=NULL)
        {
            callen=callen->next;
            len++;
        }
        int k1=k%len;
        for(int i=0;i<k1;i++)
        {
            p2=p2->next;
            if(p2==NULL)
                p2=head;
        }
        while(p2->next!=NULL)
        {
            p1=p1->next;
            p2=p2->next;
        }
        if(p1->next==NULL)
            return head;
        res=p1->next;
        p1->next=NULL;
        p2->next=head;
        return res;
    }
};

Another:

ListNode* rotateRight(ListNode* head, int k) {
    if (!head || !head->next || k == 0) return head;//nice code!!!
    ListNode *cur = head;
    int len = 1;
    while (cur->next && ++len) cur = cur->next;
    cur->next = head;
    k = len - k % len;//clever!!!
    while (k--) cur = cur->next;
    head = cur->next;
    cur->next = nullptr;
   return head; 
}

Great description!
https://discuss.leetcode.com/topic/14470/my-clean-c-code-quite-standard-find-tail-and-reconnect-the-list

    //本题极易出错!!
    //本题有个隐含条件,当k值大于list的长度时,需要取模,并根据结果进行翻转,所以一定要先求出链表的长度
    //本题两种解法:
    //解法一:求出链表长度后,更新k,然后利用双指针,一快一慢,找到要分割的点,将链表一分为二。
    //注意一个问题,新求出的k如果等于0,代表不需要翻转,直接返回即可
    //解法二:在求链表长度时,只需遍历到尾节点,并将尾节点和头结点相连,
    //剩下的任务只需要一个指针,找到分割的节点,将节点的next置位null,返回节点的原next即可
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值