zoukankan      html  css  js  c++  java
  • LF.319.Delete Node At Index

    Delete the node at the given index for the given linked list.

    Examples

    [1, 2, 3], delete at 1 --> [1, 3]

    [1, 2, 3], delete at 4 --> [1, 2, 3]

    [1, 2, 3], delete at 0 --> [2, 3]

     1 public class Solution {
     2   public ListNode deleteNode(ListNode head, int index) {
     3     // Write your solution here
     4     //corner case
     5     if (head == null || index < 0) {
     6         return head ;
     7     }
     8     int length = getLength(head) ;
     9     //corner case
    10     if (length < index +1 ) {
    11         return head ;
    12     }
    13     ListNode dummy = new ListNode(0);
    14     dummy.next = head ;
    15     ListNode curr = dummy ;
    16     int counter = 0 ;
    17     /*
    18             [1, 2, 3], delete at 1 --> [1, 3]
    19     d/c----->         counter = 0
    20              c-->     counter = 1
    21     */
    22     while(curr != null && curr.next != null){
    23         if (counter == index) {
    24             curr.next = curr.next.next ;
    25             break ;
    26         }
    27         curr = curr.next ;
    28         counter++;
    29     }
    30     return dummy.next ;
    31   }
    32   private int getLength(ListNode head){
    33     if (head == null) {
    34         return 0;
    35     }
    36     ListNode curr = head ;
    37     int res = 0 ;
    38     while(curr != null){
    39         curr = curr.next ;
    40         res++;
    41     }
    42     return res ;
    43   }
    44 }
  • 相关阅读:
    初窥语义搜索
    爬取菜谱网站
    paramiko简介
    软件项目结构规范
    paramiko 远程执行多个命令
    python 中in 的 用法
    spring依赖(部分)
    ModelAndView的部分回顾
    SringMVC 国际化
    spring事物配置,声明式事务管理和基于@Transactional注解的使用
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8656829.html
Copyright © 2011-2022 走看看