美文网首页
Leetcode系列之链表(10)

Leetcode系列之链表(10)

作者: FisherTige_f2ef | 来源:发表于2019-10-28 23:25 被阅读0次

    题目:

    将给定的链表向右转动k个位置,k是非负数。

    例如:

    给定1->2->3->4->5->null , k=2,

    返回4->5->1->2->3->null。

    思路:

    1.先遍历整个链表求出长度len

    2.将整个链表形成一个环

    3.走到len-k处断开链表返回即可

    代码:

    /**

    * Definition for singly-linked list.

    * public class ListNode {

    *    int val;

    *    ListNode next;

    *    ListNode(int x) {

    *        val = x;

    *        next = null;

    *    }

    * }

    */

    public class Solution {

        public ListNode rotateRight(ListNode head, int n) {

            if(head == null || n == 0){

                return head;

            }

            ListNode temp= head;

            ListNode temp_1= null;

            int num= 0;

            while(temp!=null){

        num++;

        temp_1=temp;

        temp= temp.next;

            }

            n= n % num;

            if(n == 0){

                return head;

            }

            ListNode result= head;

            for(int i=0;i<num-n-1;i++){

                head= head.next;

            }

            temp= head.next;

            temp_1.next= result;

            result= temp;

            head.next= null;

            return result;

            }

    }

    相关文章

      网友评论

          本文标题:Leetcode系列之链表(10)

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