leetCode练习(61)

来源:互联网 发布:网络真人赌博骗局 编辑:程序博客网 时间:2024/05/16 15:45
题目:Rotate List
难度:medium
问题描述:

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.

Subscribe to see which companies asked this question

解题思路:
先找到len,然后tail与head相连,再在正确的地方断开。难点在于怎么找到断开的地方。一是从tail再次走len-k%len步,而是在最开始的找到tail时,就将整个链表用ArrayList存起来,再直接提出断点。第二个办法是明显的空间换时间~
方法一代码如下:
public class ListNode{int val;ListNode next;ListNode(int x){val=x;}}public ListNode rotateRight(ListNode head, int k) {if(head==null){return head;}        ListNode temp=head;        int len=1;        while(temp.next!=null){        temp=temp.next;        len++;        }           temp.next=head;        k=k%len;        for(int i=0;i<len-k-1;i++){        head=head.next;        }        temp=head;        head=head.next;        temp.next=null;        return head;    }
方法二代码如下:
public ListNode rotateRight3(ListNode head, int k) {if(head==null){return head;}ListNode tail=head;int len=1;ArrayList<ListNode> list=new ArrayList<>();while(tail.next!=null){list.add(tail);tail=tail.next;len++;}list.add(tail);tail.next=head;k=k%len;k=len-k-1;System.out.println("k="+k);tail=list.get(k);head=tail.next;tail.next=null;return head;}


0 0