leetcode61-旋转链表

原题

给定一个链表,旋转链表,将链表每个节点向右移动 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

解法

思想

连接成环,找到新起点和终点。

代码

/**
 * 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 cur = head;
        int size = 1;
        //找到尾节点
        while(cur.next!=null){
            size++;
            cur = cur.next;
        }
        //连接成环
        cur.next = head;
        //找到新的尾节点
        for(int i = 0;i<size-(k%size);i++){
            cur = cur.next;
        }
        //新的头节点
        ListNode result = cur.next;
        cur.next = null;
        return result;
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode61-%e6%97%8b%e8%bd%ac%e9%93%be%e8%a1%a8/

(0)
彭晨涛彭晨涛管理者
上一篇 2019年12月16日
下一篇 2019年12月18日

相关推荐

发表回复

登录后才能评论