"061-rotate list (revolving single linked list)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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
k = 2
and,
Return 4->5->1->2->3->NULL
.
Main Topic
Rotate a single linked list to the right, rotate the k position, K non-negative.
Thinking of solving problems
Connect to the list header with a secondary root node, find the precursor of the first node to be moved, and then prev all the nodes after the prev to root, and then form a single linked list after rotation.
Code Implementation
Linked list Node class
publicclass ListNode { int val; ListNode next; ListNode(int x) { val = x; }}
Algorithm implementation class
Public classSolution { PublicListNodeRotateright(ListNode Head,intN) {if(Head = =NULL|| N <1) {returnHead } ListNode root =NewListNode (0); Root.next = head; ListNode p = root; ListNode q = root;intCount =0; for(inti =0; I <=n; i++) {p = p.next; count++;if(p = =NULL) {count--;the number of data in the list, except for the head node.n = n% count;//number of bits actually to be placed //Prepare to start the shift againi =0; p = head; } }//Find the first node to be swapped for a precursor //q is the precursor of the first node to be exchanged while(P! =NULL) {p = p.next; Q = q.next; } p = q; Q = root;if(P! =NULL&& P.next! =NULL) {//have a node to shiftListNode node; while(P.next! =NULL) {//Remove the junction.node = P.next; P.next = Node.next;//Connect to the node .Node.next = Q.next; Q.next = node; q = node;//Last moved node} }returnRoot.next; }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47182717"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
leetcode-Interview Algorithm classic-java implementation "" 061-rotate list (rotate single linked list)