Leetcode初学——旋转链表

左心房为你撑大大i 提交于 2020-02-13 03:16:44

题目:

分析:

以1->2->3->4->5  k=2为例

将链表首尾相连

将head和end依次向后移n-k个位置  n为原链表长度

在这里需要移3个位置

再将end 的next改为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) {
        ListNode end=head;
        //当链表为空时,直接返回
        if(head==null) return head;
        int n=1;
        while(end.next!=null){
            n++;
            end=end.next;
        }
        k=k%n;
        //当k的余数为0时,链表不需要移动,直接返回head
        if(k==0)return head;
        end.next=head;
        for(int i=0;i<n-k;i++){
            head=head.next;
            end=end.next;
        }
        end.next=null;
        return head;
    }
}

结果:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!