LeetCode——Rotate List,leetcoderotate

來源:互聯網
上載者:User

LeetCode——Rotate List,leetcoderotate

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.

原題連結:https://oj.leetcode.com/problems/rotate-list/

得到鏈表長度,鏈表指向尾節點,將鏈表首尾相連,向右k%len,得到結果鏈表的尾節點。

public class RotateList {public static void main(String[] args) {ListNode head = new ListNode(1);ListNode head1 = new ListNode(2);ListNode head2 = new ListNode(3);ListNode head3 = new ListNode(4);ListNode head4 = new ListNode(5);head.next = head1;head1.next = head2;head2.next = head3;head3.next = head4;//while(head != null){//System.out.println(head.val);//head = head.next;//}ListNode ln = new RotateList().rotateRight(head, 2);while(ln != null){System.out.println(ln.val);ln = ln.next;}}public ListNode rotateRight(ListNode head, int n) {if(head == null)return head;int len = 1;ListNode tmp = head;while(tmp.next != null){tmp = tmp.next;len ++;}tmp.next = head;n %= len;int step = len - n;while(step > 0){tmp = tmp.next;step --;}head = tmp.next;tmp.next = null;return head;}}// Definition for singly-linked list. class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.