算法修炼之旋转链表

一. 题目描述

leetcode : 旋转链表

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

示例 1:
		输入: 1->2->3->4->5->NULL, k = 2
		输出: 4->5->1->2->3->NULL
		解释:
		向右旋转 1 步: 5->1->2->3->4->NULL
		向右旋转 2 步: 4->5->1->2->3->NULL

示例 2:	
		输入: 0->1->2->NULL, k = 4
		输出: 2->0->1->NULL
		解释:
		向右旋转 1 步: 2->0->1->NULL
		向右旋转 2 步: 1->2->0->NULL
		向右旋转 3 步: 0->1->2->NULL
		向右旋转 4 步: 2->0->1->NULL

二. 算法分析

1. 常规解法

结合实例,很容易想到,我们只需要找到链表向右移动 k 个位置后的分界结点,然后将其断开再重连即可。
如实例一:我们找到结点3和结点4,然后将结点3指向null,再找到结点4后面的末结点5,将5指向头结点1,即可完成算法.

    public ListNode rotateRight(ListNode head, int k) {
        //base cases
        if (head == null || head.next == null) return head;
        //find the length of linklist
        ListNode nhead = head;
        int len = 0;
        while (nhead != null) {
            ++len;
            nhead = nhead.next;
        }
        //if (k % len == 0) there is no need to rotate
        if (k % len == 0) return head;
        //find the last node of new linklist
        k = len - (k % len) - 1;
        ListNode lnode = head;
        while (k > 0) {
            --k;
            lnode = lnode.next;
        }
        //find the first node of new linklist
        nhead = lnode;
        while (nhead.next != null) {
            nhead = nhead.next;
        }
        //generate the new linklist
        nhead.next = head;
        nhead = lnode.next; // the new first node
        lnode.next = null;
        return nhead;
    }

2. 循环链表

根据示例,我们可以先将原链表变成单循环链表,然后找到最终链表的尾结点,将其指向null,即可完成。

注意:
1. 当 k <= n ,新结点尾: (n - k)th;
2. 当 k > n , 新结点尾: n - (k % n)th;

剪枝:
如果 (k % n == 0),直接返回头结点

 public ListNode rotateRight(ListNode head, int k) {
        //base cases
        if (head == null || head.next == null) return head;
        //generate the circulate list
        ListNode old_tail = head;
        int n;
        for (n = 1; old_tail.next != null; n++) {
            old_tail = old_tail.next;
            //old_tail.next = head;
        }
        //pruning
        if (k % n == 0) return head;
        else old_tail.next = head;
        //find the new tail node
        k = n - (k % n);
        ListNode new_tail = old_tail;
        while (k > 0) {
            --k;
            new_tail = new_tail.next;
        }
        ListNode new_head = new_tail.next;
        new_tail.next = null; //let the new_head point to null
        return new_head;
    }

三. 总结

其实两种方法殊途同归,链表算法主要就是在写代码的时候要防止空指针异常,慢慢解决就好了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值