赞
踩
今天来学习的算法题是leecode61旋转链表,是一道简单的入门题,话不多说!直接上!
原子本来写了一大推书面解释!可惜都没啦!我直接上图,如果有疑问的话私信我交流一下!
在这里插入图片描述
public class Leecode62 { public static void main(String[] args) { } /** * 62旋转链表 */ class Solution { public ListNode rotateRight(ListNode head, int k) { if (k == 0 || head == null || head.next == null) { return head; } ListNode tail = head; ListNode newtail = head; ListNode newhead; int n = 1; /** * 成环 */ //通过循环找到了链表中的尾节点 while(tail.next != null){ tail = tail.next; n++; } //连接尾节点和头节点至此形成环 tail.next = head; /** * 旋转链表 */ // 找到断开环的位置 //计算方式:n为链表中的元素个数,k%n是考虑到是一个环的情况下,旋转的次数可能会大于链表长度的情况 //所以使用取余操作来确保在规定的范围内进行操作 for(int i = 0; i < (n - k % n - 1); i++){ newtail = newtail.next; } // 新的头结点指向断开环的位置 newhead = newtail.next; newtail.next = null; return newhead; } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。