Leetcode——61. Rotate List

来源:互联网 发布:淘宝注册还要拨打号码 编辑:程序博客网 时间:2024/06/16 17:26

题目

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即可
0 0