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 }
原文地址:https://www.cnblogs.com/davidnyc/p/8656829.html