File tree Expand file tree Collapse file tree 1 file changed +22
-10
lines changed Expand file tree Collapse file tree 1 file changed +22
-10
lines changed Original file line number Diff line number Diff line change @@ -328,14 +328,29 @@ class MyLinkedList {
328328 return currentNode. val;
329329 }
330330
331- // 在链表最前面插入一个节点,等价于在第0个元素前添加
332331 public void addAtHead (int val ) {
333- addAtIndex(0 , val);
332+ ListNode newNode = new ListNode (val);
333+ newNode. next = head. next;
334+ head. next = newNode;
335+ size++ ;
336+
337+ // 在链表最前面插入一个节点,等价于在第0个元素前添加
338+ // addAtIndex(0, val);
334339 }
335340
336- // 在链表的最后插入一个节点,等价于在(末尾+1)个元素前添加
341+
337342 public void addAtTail (int val ) {
338- addAtIndex(size, val);
343+ ListNode newNode = new ListNode (val);
344+ ListNode cur = head;
345+ while (cur. next != null ) {
346+ cur = cur. next;
347+ }
348+
349+ cur. next = newNode;
350+ size++ ;
351+
352+ // 在链表的最后插入一个节点,等价于在(末尾+1)个元素前添加
353+ // addAtIndex(size, val);
339354 }
340355
341356 // 在第 index 个节点之前插入一个新节点,例如index为0,那么新插入的节点为链表的新头节点。
@@ -407,7 +422,7 @@ class MyLinkedList {
407422
408423 public int get (int index ) {
409424 // 判断index是否有效
410- if (index< 0 || index >= size){
425+ if (index>= size){
411426 return - 1 ;
412427 }
413428 ListNode cur = this . head;
@@ -441,10 +456,7 @@ class MyLinkedList {
441456 if (index> size){
442457 return ;
443458 }
444- // index小于0
445- if (index< 0 ){
446- index = 0 ;
447- }
459+
448460 size++ ;
449461 // 找到前驱
450462 ListNode pre = this . head;
@@ -462,7 +474,7 @@ class MyLinkedList {
462474
463475 public void deleteAtIndex (int index ) {
464476 // 判断索引是否有效
465- if (index< 0 || index >= size){
477+ if (index>= size){
466478 return ;
467479 }
468480 // 删除操作
You can’t perform that action at this time.
0 commit comments