LeetCode进阶之路（Rotate List）

63人阅读 评论(0)

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.

public ListNode rotateRight(ListNode head, int k) {

ListNode result = new ListNode(-1);
ListNode first = result;
ListNode third = result;
return result.next;
}
}
int len = 1;
while(result.next != null) {
len++;
result = result.next;
}
int i = 0;
while(i < len-k) {
i++;
first = first.next;
}
third.next = first;
int j = 1;
while(j < len-1-k) {
second = second.next;
j++;
}
second.next = null;

ListNode flag = third;
while(flag.next != null) {
flag = flag.next;
}

return third.next;

}

public ListNode rotateRight(ListNode head, int n) {
int len = 0;

while(countlen!=null){
len++;
countlen = countlen.next;
}

n = n%len;
if(n==0)

for(int i = 0; i < n; i++)
fast = fast.next;

while(fast.next!=null){
slow = slow.next;
fast = fast.next;
}

slow.next = null;

}

public ListNode rotateRight(ListNode head, int n) {

if (head == null || n == 0)
while (p.next != null) {
len++;
p = p.next;
}
p.next = head; //form a loop
n = n % len;
for (int i = 0; i < len - n; i++) {
p = p.next;
} //now p points to the prev of the new head
p.next = null;
}

种一棵树最好的时间是十年前，其次是现在！

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：8154次
• 积分：759
• 等级：
• 排名：千里之外
• 原创：70篇
• 转载：3篇
• 译文：0篇
• 评论：2条
文章分类
评论排行
最新评论