zoukankan      html  css  js  c++  java
  • LeetCode -- Rotate List

    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 and k = 2,
    return 4->5->1->2->3->NULL.

    Analysis:

    给出一个单链表,旋转链表的从右边数k个位置,将他们按顺序放到左边。k是个非负的整数。

    注意一些特殊情况:

    如当给出的k值比链表长度还大怎么办?当k=0怎么办?

    Answer:

    /**
     * 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 = 0;
            ListNode p = head;
            ListNode end = null;
            while(p != null) {
                if(p.next == null) 
                    end = p;
                p = p.next;
                len++;
            }
            k %= len;
            if(k == 0)
                return head;
            int pre = len - k;
            len = 0;
            p = head;
            while(len +1 < pre) {
                p = p.next;
                len++;
            }
            ListNode q = p.next;
            end.next = head;
            p.next = null;
            return q;
        }
    }
  • 相关阅读:
    网络编程 TCP
    网络编程之 osi七层协议
    面向对象之元类,单例
    面向对象之异常处理
    面向对象之多态
    面向对象之封装
    mysql 单表查询
    mysql 行(记录)的详细操作
    mysql 库表的操作
    数据库初识
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/5446466.html
Copyright © 2011-2022 走看看