【leetcode】 61. 旋转链表

 

 

其实就是将链表从 第 size-k个位置截断,然后将后半部分拼接到前半部分。(其中size是链表的长度,k需要处理一下,k=size%k,如果k=0的话,就相当于是没有移动)

/**
 * 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 cur = head,kNode=null,kNextNode=null,lastNode=null;
        int size = 0;
        while(cur!=null){
            size++;
            lastNode = cur;
            cur = cur.next;
        }
        if(size==0)
           return head;
        k = k%size;
        if (k==0)
            return head;
        k = size-k;
        cur = head;
        size = 0;
        while(cur!=null){
            size++;
            if (size==k){
                kNode = cur;
                kNextNode = cur.next;
                break;
            }
            cur = cur.next;
        }
        lastNode.next = head;
        kNode.next = null;
        return kNextNode;
        }
}

 

posted @ 2021-10-06 21:45  一去二三浪里小白龙  阅读(63)  评论(0编辑  收藏  举报
//增加一段JS脚本,为目录生成使用