zoukankan      html  css  js  c++  java
  • [leedcode 61] 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.

    /**
     * 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) {
            //本题极易出错!!
            //本题有个隐含条件,当k值大于list的长度时,需要取模,并根据结果进行翻转,所以一定要先求出链表的长度
            //本题两种解法:
            //解法一:求出链表长度后,更新k,然后利用双指针,一快一慢,找到要分割的点,将链表一分为二。
            //注意一个问题,新求出的k如果等于0,代表不需要翻转,直接返回即可
            //解法二:在求链表长度时,只需遍历到尾节点,并将尾节点和头结点相连,
            //剩下的任务只需要一个指针,找到分割的节点,将节点的next置位null,返回节点的原next即可
            /*解法一:
            if(head==null||k==0) return head;
            int len=0;
            ListNode temp=head;
            while(temp!=null){
                temp=temp.next;
                len++;
            }
      
            int dis=k%len;
            if(dis==0) return head;/////
            ListNode fast=head;
            ListNode slow=head;
            temp=head;
            while(dis>0){
                fast=fast.next;
                dis--;
            }
            while(fast.next!=null){
                fast=fast.next;
                slow=slow.next;
            }
            temp=slow.next;
            slow.next=null;
            fast.next=head;
            return temp;*/
            if(head==null||k==0) return head;
            int len=1;
            ListNode temp=head;
            while(temp.next!=null){
                len++;
                temp=temp.next;
            }
            temp.next=head;
            int dis=len-k%len;
            while(dis>0){
                temp=temp.next;
                dis--;
            }
            head=temp.next;
            temp.next=null;
            return head;
            
        }
    }
  • 相关阅读:
    analysis of algorithms
    Measurement of Reflected Radiation
    lecture 5
    lecture 3
    字符串
    Emission of Radiation辐射发射
    Electromagnetic Radiation(EMR) 电磁辐射
    Linux FTP服务器-VSFTPD虚拟用户配置
    jenkins notes
    python nose使用记录
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4642773.html
Copyright © 2011-2022 走看看