题目描述
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
我的想法是找到要倒置的第一个元素位置,然后再由末尾元素指向head。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if(head == null || head.next == null)
return head;
ListNode cur = head;
int count = 1;
while(cur.next != null) {
cur = cur.next;
count++;
}
ListNode p = head;
ListNode pre = new ListNode(0);
pre.next = p;
int s = count - n;
while(s != 0){
p = p.next;
pre = pre.next;
s--;
}
cur.next = head;
pre.next = null;
return p;
}
}
运行是如下结果:
查看别人通过的代码:
public class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null||k==0)
return head;
int len = 0;
ListNode cur = head;
ListNode last = null;
while(cur!=null){
len++;
last = cur;
cur = cur.next;
}
if(k>=len&&len!=0)
k %= len;
if(k==0)
return head;
last.next = head;//形成环路
cur = head;//因为是右移动,所以从头开始遍历到倒数第k个元素
for(int i = 1;i<=len-k;i++){
last = cur;
cur = cur.next;
}
//cur是头
last.next = null;
return cur;
}
}
好像没啥区别。。。