leetcode61

3/27/2021 算法链表

# 解题思路

很简单的思路,把链表合成环,然后遍历就好了

# 代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        ListNode tmp=head;
        ListNode ans =head;
        int count = 0;
        if(head==null||head.next==null)
            return head;
        while(head.next!=null){
            ++count;
            head=head.next;
        }
        head.next=ans;
        ++count;
        while(k%count!=count-1){
            ++k;
            ans=ans.next;
        }
        tmp=ans.next;
        ans.next=null;
        ans=tmp;
        return ans;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33