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

    这道题有点循环移位的意思

    将链表向右移动k个节点,右边的节点放到左边。返回新的链表头结点

    思路

    遍历链表,找出长度length,对k取余,k = k % length,利用双指针一个frontPtr在前面k个节点,后一个behindPtr从head开始,frontPtr到链表结尾。forntPtr指向头结点,头结点改为behindPtr所指下一个节点。behindPtr下一个节点置为空。返回头结点即可

     1 public class Solution {
     2     public ListNode rotateRight(ListNode head, int n) {
     3         if(head == null || head.next == null || n == 0)
     4             return head;
     5         ListNode behindPtr = head;
     6         ListNode frontPtr = head;
     7         
     8         int count = 0;
     9         ListNode temp = head;
    10         int length = 1;
    11         while(temp.next != null){
    12             length ++;
    13             temp = temp.next;
    14         }//while
    15         n = n % length;
    16         while(count < n && frontPtr.next != null){
    17             frontPtr = frontPtr.next;
    18             count ++;
    19         }//while
    20         while(frontPtr.next != null){
    21             frontPtr = frontPtr.next;
    22             behindPtr = behindPtr.next;
    23         }//while
    24         frontPtr.next = head;
    25         head = behindPtr.next;
    26         behindPtr.next = null;
    27                 
    28         return head;
    29     }
    30 }
  • 相关阅读:
    JavaEE 第四周
    JavaEE 第三周
    JavaEE 第二周
    JavaEE 第一周
    js字符串方法
    javaee项目库存管理系统总结
    javaee期末团队项目库存管理系统概要信息
    JAVAEE第十一周
    JSON
    Facelets
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4235568.html
Copyright © 2011-2022 走看看