LeetCode(61)-Rotate List

版权声明:XiangYida https://blog.csdn.net/qq_36781505/article/details/83625459

61. Rotate List

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

嗯?这个题的意思是给一个链表,然后旋转一下,怎么旋转呢?就是最后一个节点变为头结点,其他的节点顺序不变,放在头结点的后面。然后参数k指的是旋转的次数。
这个题不难,只是有个小小关键的地方,当选择次数等于链表的长度的时候,链表又回到了最初的状态,所以需要对参数k求余,不然,等着超时吧。_

/**
 * Definition for singly-linked list.
 * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
   public ListNode rotateRight(ListNode head, int k) {
       if(head==null||null==head.next)return head;
        ListNode l=head;
        int j=1;
        while (null!=(l=l.next))j++;
        k=k%j;
        for (int i = 0; i <k; i++) {
            //最后一个节点
            ListNode node=null;
            //倒数第二个节点
            ListNode node1 = null;
            //头节点
            ListNode h=head;
            while (null!=head.next){
               node=head.next;
               node1=head;
               head=head.next;
            }
            node1.next=null;
            node.next=h;
            head=node;
        }
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36781505/article/details/83625459