Leetcode初学——旋转链表

题目:

分析:

以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;
    }
}

结果:

发布了57 篇原创文章 · 获赞 3 · 访问量 1052

猜你喜欢

转载自blog.csdn.net/qq_39377543/article/details/104267746