Rotate List @ LeetCode

Source: Internet
Author: User

Loop and cutting of linked lists

Package Level3; import Utility. listNode;/***** Rotate List ** 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 class S61 {public static void main (String [] args) {ListNode head = new ListNode (1); ListNode n2 = new ListNode (2 ); listNode n3 = new ListNode (3); ListNode n4 = New ListNode (4); ListNode n5 = new ListNode (5); head. next = n2; n2.next = n3; n3.next = n4; n4.next = n5; ListNode rotateHead = rotateRight (head, 2); rotateHead. print ();} public static ListNode rotateRight (ListNode head, int n) {if (head = null) {return null;} ListNode back = head; ListNode front = head; listNode end = head; // first change the linked list to a circular linked list while (front. next! = Null) {front = front. next;} end = front; // record the front of the original end node. next = head; // forming the ring front = head; // restore the front pointer // make the front n distances before the back for (int I = 0; I <n; I ++) {front = front. next;} // move the while (front! = End) {front = front. next; back = back. next;} ListNode rotateHead = back. next; // find the chain table header back after rotate. next = null; // The return rotateHead of the open loop linked list ;}}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.