leetcode 旋转单链表

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

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

关键:

1、3个指针,一个指向打断处的后一个结点,并且将要成为新链表头,ListNode* front,用于return;一个指向打断处的前一个节点,并成为链表尾,ListNode* back,用于将尾节点的next置空;一个为当前的尾巴节点,ListNode* link 用于将当前尾节点与头节点连起来。

2、2次O(n)级的遍历,第一次用于求出链表长度,进而求出front和end位置;第二次用于将front和end移动到求出的位置

3、4种特殊情况,一是链表长度为0;二是链表长度为1;三是旋转的步数大于链表长度时要取模;四是旋转步数取模后为0时直接返回。

/**
 * 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;
        }else if(head->next==NULL){
            return head;
        }
        
        ListNode* front=head;
        ListNode* back=head;
        ListNode* link=head;
        
        int len=1;
        while(link->next!=NULL){
            len++;
            link=link->next;
        }
        
        k=k%len;
        if(k==0){
            return head;
        }
        int step=len-k-1;
        front=front->next;
        
        for(int i=0;i<step;i++){
            back=back->next;
            front=front->next;
        }
        
        back->next=NULL;
        link->next=head;
        return front;
    }
};

猜你喜欢

转载自www.cnblogs.com/zealousness/p/9664725.html
今日推荐