"061-rotate list (rotating single linked list)"
" leetcode-interview algorithm classic-java Implementation" "All topic Directory Index"
Original title
Given a list, rotate 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.
The main effect of the topic
Rotate one single linked table to the right, rotate K position, K non-negative.
ideas for solving problems
Using an auxiliary root node to connect to the header of the chain, first find the first node to move the precursor prev, and then all the nodes after prev to root, and then form a rotating single linked list.
Code Implementation
Linked list Node class
public class ListNode {
int val;
ListNode Next;
ListNode (int x) {val = x;}
}
Algorithm implementation class
public class Solution {public ListNode rotateright (listnode head, int n) {if (head = = NULL | | n < 1) {
return head;
ListNode root = new ListNode (0);
Root.next = head;
ListNode p = root;
ListNode q = root;
int count = 0;
for (int i = 0; I <=n; i++) {p = p.next;
count++; if (p = = null) {count--;//The number of data N = n% count after header node in the linked list;//The actual number of digits to position/
The new starting displacement makes preparation i = 0;
p = head;
The precursor of the first node to be exchanged//q is the precursor of the first node to be exchanged (p!= null) {p = p.next;
Q = q.next;
} p = q;
Q = root;
if (p!= null && p.next!= null) {//Has to shift node ListNode node;
while (P.next!= null) {//Remove node node = p.next;
P.next = Node.next; Connect the knot point node.next = Q.next;
Q.next = node; q = node;
The last Moving node} return root.next; }
}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, released in a new window to view the full picture.
Special Notes Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47182717"