zoukankan      html  css  js  c++  java
  • LF.366.Linked List Insert At Index

    Insert a new element at a specific index in the given linked list. The index is 0 based, and if the index is out of the list's scope, you do not need to do anything.

    Examples:

    1 -> 2 -> 3 -> null, insert 4 at index 3, --> 1 -> 2 -> 3 -> 4 -> null

    1 -> 2 -> null, insert 4 at index 0, --> 4 -> 1 -> 2 -> null

     1 public class Solution {
     2   public ListNode insert(ListNode head, int index, int value) {
     3     // Write your solution here
     4     if (head == null || index < 0) {
     5         return head;
     6     }
     7     int length = getLength(head) ;
     8     //corner case: index out of list's scope
     9     if (length < index) {
    10         return head ;
    11     }
    12     ListNode dummy = new ListNode(0);
    13     ListNode curr = dummy ;
    14     dummy.next = head ;
    15     int counter = 0 ;
    16     /*
    17          1 -> 2 -> 3-> null insert @ index = 1
    18     d/c-->
    19          c
    20     */
    21     while(curr != null ){
    22         if (counter == index) {
    23             ListNode newNode = new ListNode(value);
    24             ListNode temp = curr.next ;
    25             curr.next = newNode ;
    26             newNode.next = temp ;
    27             break ;
    28         }
    29         curr = curr.next ;
    30         counter++;
    31     }
    32     return dummy.next ;
    33   }
    34 
    35   private int getLength(ListNode head){
    36     if (head == null) {
    37         return 0;
    38     }
    39     ListNode curr = head ;
    40     int res = 0 ;
    41     while(curr != null){
    42         curr = curr.next ;
    43         res++;
    44     }
    45     return res ;
    46   }
    47 
    48 }
  • 相关阅读:
    通过组合mesh优化资源
    unity四元数
    Unity3D开发之Matrix4x4矩阵变换
    Unity用矩阵进行坐标转换
    【Unity3D的四种坐标系】
    unity里的向量
    Unity3D_场景の烘培
    本地电脑配ssh key的几个命令
    Unity两个Transparent/Diffuse渲染的半透明材质千万不要重叠呀
    new GameObject的巧妙用法
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8669158.html
Copyright © 2011-2022 走看看