zoukankan      html  css  js  c++  java
  • [LeetCode] 61. Rotate List Java

    题目:

    Given a list, rotate the list to the right by k places, where k is non-negative.

    Example:

    Given 1->2->3->4->5->NULL and k = 2,
    
    return 4->5->1->2->3->NULL.

    题意及分析:从右到左第n个点进行翻转链表。主要是要找到翻转点和翻转点前面一个点,然后将最后一个点的next设置为head,翻转点前一个点的next设置为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 n) {
            if(head == null || n==0) return head;
            int length = 1;     //记录链表有多长
            ListNode p = head;
            while(p.next != null){
                p = p.next;
                length++;
            }
            //此时p指向链表最后一个点
            n=n%length;
            if(n==0) return head;
            ListNode rotedNode = null;
            ListNode preRotate = head;
            int k=0;
            while(k<length-n-1){
                preRotate = preRotate.next;
                k++;
            }
            rotedNode = preRotate.next;
    
            preRotate.next = null;
            p.next = head;
            return rotedNode;
        }
    } 
  • 相关阅读:
    济南学习 Day5 T3 晚
    Codevs 1043 ==洛谷 P1004 方格取数
    济南学习 Day 5 T2 晚
    济南学习 Day 5 T1 晚
    济南学习 Day 5 T3 am
    济南学习 Day 5 T2 am
    LeetCode Weekly Contest 8
    poj-1410 Intersection
    leetcode-Warm Up Contest-Aug.21
    poj-1384 Piggy-Bank
  • 原文地址:https://www.cnblogs.com/271934Liao/p/8256891.html
Copyright © 2011-2022 走看看