leetcode 61 --Rotate List 链表 循环/断开 翻转

来源:互联网 发布:手机淘宝网的货到付款 编辑:程序博客网 时间:2024/06/03 16:44

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

对于这题我们首先需要遍历链表,得到链表长度n,因为k可能大于n,所以我们需要取余处理,然后将链表串起来形成一个环,在遍历n - k % n个节点,断开,就成了。比如说,k等于2,我们遍历到链表结尾之后,连接1,然后遍历 5 - 2 % 5个字节,断开环,下一个节点就是新的链表头了。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode rotateRight(ListNode head, int k) {        if(head==null||head.next==null||k==0) return head;        ListNode curr=head;        int len=1;        while(curr.next!=null){ //循环跳出的时候指针指向最后一个元素            curr=curr.next;            len++;        }        k=k%len;        curr.next=head;        for(int i=0;i<len-k;i++){            curr=curr.next;        }        head=curr.next;        curr.next=null;        return head;    }}
1 0
原创粉丝点击