Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
/**
* 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 || n==0) {
return head;
}
ListNode p1 = head;
ListNode p2 = head;
int t = n;
int length = 0;
boolean over = false;
while(t-->0) {
p2 = p2.next;
length++;
if(p2==null) {
over = true;
break;
}
}
if(over) {
n = n%length;
if(n==0) {
return head;
}
t = n;
p2 = head;
while(t-->0) {
p2 = p2.next;
}
}
while(p2.next!=null) {
p1 = p1.next;
p2 = p2.next;
}
ListNode p3 = p1.next;
p1.next = null;
p1 = p3;
while(p1.next!=null) {
p1 = p1.next;
}
p1.next = head;
return p3;
}
}
===========
/**
* 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) {
return head;
}
int len = 1;
ListNode p = head;
while (p.next != null) {
p = p.next;
len += 1;
}
ListNode tail = p;
if (k % len == 0) return head;
int t = len - k % len;
p = head;
while (t-- > 1) {
p = p.next;
}
ListNode newHead = p.next;
p.next = null;
tail.next = head;
return newHead;
}
}
For example:
Given
1->2->3->4->5->NULL
and k = 2
,return
4->5->1->2->3->NULL
./**
* 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 || n==0) {
return head;
}
ListNode p1 = head;
ListNode p2 = head;
int t = n;
int length = 0;
boolean over = false;
while(t-->0) {
p2 = p2.next;
length++;
if(p2==null) {
over = true;
break;
}
}
if(over) {
n = n%length;
if(n==0) {
return head;
}
t = n;
p2 = head;
while(t-->0) {
p2 = p2.next;
}
}
while(p2.next!=null) {
p1 = p1.next;
p2 = p2.next;
}
ListNode p3 = p1.next;
p1.next = null;
p1 = p3;
while(p1.next!=null) {
p1 = p1.next;
}
p1.next = head;
return p3;
}
}
===========
/**
* 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) {
return head;
}
int len = 1;
ListNode p = head;
while (p.next != null) {
p = p.next;
len += 1;
}
ListNode tail = p;
if (k % len == 0) return head;
int t = len - k % len;
p = head;
while (t-- > 1) {
p = p.next;
}
ListNode newHead = p.next;
p.next = null;
tail.next = head;
return newHead;
}
}
没有评论:
发表评论