LeetCode 61. Rotate List(链表题目--复杂)

LeetCode 61. Rotate List(链表题目)

题目描述:

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

Example:

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)判断k>n(链表结点数量),以及如何处理---需要统计链表长度,同时不停地旋转,所以形成一个环是不错的选择(便利一遍链表,技能统计次数,同时也能形成一个环);2)判断真正需要进行循环的次数(包括k与n的大小,如果k<n,number=size-k,如果 k>=n,number=size-(k%n)).3)确定需要断开的点,重新确定新的结点指向即可。

具体代码:

/**
 * 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 || !head->next)
            return head;      
        ListNode* p=head;
        int size=1;//统计个数的初始值应该从1开始,可以画一画
        
        //遍历一遍链表统计长度,以及确定最后一个结点p
        while(p->next)
        {
            p=p->next;
            size++;
        }  
        //形成一个环,方便后续操作(但一定确定好头结点)
        p->next=head;
        
        int number = 0;
        if(size - k > 0)
            number = size - k;
        else{
            number = size - (k % size);
        }
        
        //找到需要断开的前一个结点(需要计算好次数)
        for(int i=0;i<number-1;i++)
            head=head->next;
        
        //确定新的头结点,尾结点,给予正确的指向(尾结点指向NULL)
        ListNode* res=head->next;
        head->next=NULL;
        
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_20110551/article/details/81437172