61. 旋转链表

题目

61. 旋转链表

题解


代码:

public class code61 {

    public static ListNode rotateRight(ListNode head, int k) {
        // base cases
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return head;
        }

        // close the linked list into the ring
        ListNode old_tail = head;
        int n;
        for (n = 1; old_tail.next != null; n++) {
            old_tail = old_tail.next;
        }
        old_tail.next = head;

        // find new tail : (n - k % n - 1)th node
        // and new head : (n - k % n)th node
        ListNode new_tail = head;
        for (int i = 0; i < n - k % n - 1; i++) {
            new_tail = new_tail.next;
        }
        ListNode new_head = new_tail.next;

        // break the ring
        new_tail.next = null;

        return new_head;
    }

    public static ListNode createList_1() {
        ListNode head = new ListNode(1);
        ListNode cur = head;
        for (int i = 2; i <= 5; i++) {
            cur.next = new ListNode(i);
            cur = cur.next;
        }
        cur.next = null;
        return head;
    }

    public static ListNode createList_2() {
        ListNode head = new ListNode(0);
        ListNode cur = head;
        for (int i = 1; i <= 2; i++) {
            cur.next = new ListNode(i);
            cur = cur.next;
        }
        cur.next = null;
        return head;
    }

    public static void print(ListNode node) {
        if (node == null) {
            return;
        }
        ListNode current = node;
        while (current != null) {
            System.out.print(current.val + " -> ");
            current = current.next;
        }
        System.out.println("NULL");
    }

    public static void main(String[] args) {
        ListNode head_1 = createList_1();
        print(head_1);
        int k_1 = 2;
        ListNode res_1 = rotateRight(head_1, k_1);
        print(res_1);

        System.out.println();

        ListNode head_2 = createList_2();
        print(head_2);
        int k_2 = 4;
        ListNode res_2 = rotateRight(head_2, k_2);
        print(res_2);
    }

}

参考:

  1. 旋转链表——题解一
  2. Leetcode 61:旋转链表(最详细解决方案!!!)——题解二
  3. Rotate List (旋转链表,切断)——题解三
全部评论

相关推荐

我是985研究生,最近学校在组织开题,大家都在非常紧张地准备,但我一直进入不了状态,很想做但是心又很浮躁。但我的室友们感觉都非常认真,每天醒来就开始看论文,睡着前最后一件事还是在看论文,我非常焦虑。我感觉自己甚至有点把大家当做假想敌了。这种比较心态还存在于生活的各种方面:看到有钱的同学会非常羡慕,看到朋友圈里面环游世界的留学生同学也会羡慕,看到那些工作后有自己的钱而过上较为阔绰的生活的时候还是羡慕,就仿佛只有自己一个人在阴暗爬行。而且这些比较是每时每刻的,为了不比较,我已经关闭了朋友圈,但是每次偶尔刷一下还是会难受很久。我知道比较是偷走幸福的小偷,但我好像控制不了,感觉自己是一个偷窥别人生活的...
若怜君欢:担心开题搞砸了,幻想拥有别人的生活,本质上是因为自卑,楼主小时候大概率是留守儿童或者父母关系很紧张,导致楼主没有安全感、焦虑、内耗。 这样的情况最好的办法就是建立自信和降低期待,建立自信不是一蹴而就,而是循序渐进,比如告诉自己允许自己第一次没把事情做好,失败了能搞清楚其中缘由而不是全盘否定自己,失败不是终点,放弃才是;降低期待只要记住一句话即可,能伴随你一生的,只有经验和学识,所以你对事情的态度应该更多地去思考它是否能带来学识和经验的增长,而不是仅仅用短期的利益作为唯一期待。 人生不是一成不变的,它是可以迭代更新的,去归纳总结自身的不足并结合实际去改进,去尝试一些新的思路和方法,不要固执钻牛角尖,也不要反复横跳,为自己设立一个高度聚集的精神内核,内核之上可以去尝试一切有利于自己更好的方式 以上就是我个人对生活的理解,共勉
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务