美文网首页
LeetCode-Rotate List

LeetCode-Rotate List

作者: 圣地亚哥_SVIP | 来源:发表于2018-10-09 20:38 被阅读0次

主要考察对链表的处理:
1、确定两个链表的长度
2、对这两个链表进行翻转

/**
 * 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 == nullptr || head->next == nullptr)return head;
        
        int len = 0;
        auto hptr = head;
        auto hend = head;
        ListNode* end = nullptr;
        //ListNode* hptrRight = nullptr;
        while (hptr != nullptr){
            len++;
            end = hptr;
            hptr = hptr->next;
        }
        hptr = head;
        k = k%len;
        if (k == 0)return head;
        k = len-k-1;
        while (k>0){
            k--;
            hend = hend->next;
        }
        auto hptrRight = hend->next;
        
        /*
        * Rotate Two LinkList
        */
        
        end->next = head;
        hend->next = nullptr;
        
        
        head = hptrRight;
        return head;
    }
};

相关文章

网友评论

      本文标题:LeetCode-Rotate List

      本文链接:https://www.haomeiwen.com/subject/jagyaftx.html