1. 程式人生 > >【連結串列節點查詢】61. Rotate List

【連結串列節點查詢】61. Rotate List

類似於找到連結串列的倒數第k個節點,然後把前後二段連結串列倒置前後順序即可;

/**
 * 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 head;
        ListNode* temp=head;
        ListNode*last;
        int len=0;
        while(temp!=0)
        {
            len++;
            if(temp->next==NULL)
                last=temp;
            temp=temp->next;
        }
        k%=len;
        if(k==0)
            return head;
        
        int step=len-k-1;
        
        ListNode* begin=head;
        while(step>0)
        {
            begin=begin->next;
            step--;
        }
        ListNode* ans=begin->next;
        last->next=head;
        begin->next=NULL;
        return ans;
    
        
    }
};