码迷,mamicode.com
首页 > 其他好文 > 详细

LF.319.Delete Node At Index

时间:2018-03-27 14:35:38      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:linked   gpo   span   r++   you   post   pre   new   amp   

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 }

 

LF.319.Delete Node At Index

标签:linked   gpo   span   r++   you   post   pre   new   amp   

原文地址:https://www.cnblogs.com/davidnyc/p/8656829.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!