61.旋转链表

/**
 * 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)
            return null;
        ListNode flag = head;
        ListNode ls1  = head;
        ListNode ls2  = head;
        int len = 0;
        while(flag != null) {
            len++;
            flag = flag.next;
        }
        k = k % len ; 
        for(int i = 0 ; i < k ; i++) {
            ls1 = ls1.next;
        }
        while(ls1.next!=null) {
            ls1 = ls1.next;
            ls2 = ls2.next;
        }
        ls1.next = head;
        ListNode ls3  = ls2.next;
        ls2.next = null;

        return ls3;
    }
}
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) return null;
        ListNode work = head;
        int count = 0;
        while (work != null) {
            count++;
            work = work.next;
        }
        k = k % count;
        if (k == 0) {
            return head;
        }
        work = head;
        ListNode pre = head;
        for (int i = 0; i < count - k; i++) {
            pre = work;
            work = work.next;
        }
        pre.next = null;
        pre = head;
        head = work;
        while (work.next != null) {
            work = work.next;
        }
        work.next = pre;
        return head;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 10:52
点赞 评论 收藏
分享
已老实求offer😫:有点像徐坤(没有冒犯的意思哈)
点赞 评论 收藏
分享
有趣的牛油果开挂了:最近这个阶段收到些杂七杂八的短信是真的烦
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务