File tree Expand file tree Collapse file tree 1 file changed +10
-8
lines changed
Expand file tree Collapse file tree 1 file changed +10
-8
lines changed Original file line number Diff line number Diff line change 11package Chap3 ;
22
3- /**
4- * 给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间内删除该结点。假设要删除的结点确实在链表中
5- */
63public class DeleteNode {
74
5+ private Node first ;
6+
87 private class Node {
98 int val ;
109 Node next ;
@@ -13,7 +12,7 @@ private class Node {
1312 /**
1413 * 常规方法,从first开始找到要删除结点的前一个结点,时间复杂度为O(n)
1514 */
16- public void deleteNode_2 (Node first , Node toBeDel ) {
15+ public void deleteNode_2 (Node toBeDel ) {
1716 if (first == null || toBeDel == null ) {
1817 return ;
1918 }
@@ -22,18 +21,21 @@ public void deleteNode_2(Node first, Node toBeDel) {
2221 first = first .next ;
2322 } else {
2423 Node cur = first ;
25- while (cur .next != toBeDel ) {
24+ // 找到被删除结点的前一个结点
25+ while (cur != null && cur .next != toBeDel ) {
2626 cur = cur .next ;
2727 }
28- // cur为toBeDel的前一个结点
29- cur .next = cur .next .next ;
28+ if (cur != null ) {
29+ // cur为toBeDel的前一个结点
30+ cur .next = cur .next .next ;
31+ }
3032 }
3133 }
3234
3335 /**
3436 * 将toBeDel的下一个结点j的值复制给toBeDel。然后将toBeDel指向j的下一个结点
3537 */
36- public void deleteNode (Node first , Node toBeDel ) {
38+ public void deleteNode (Node toBeDel ) {
3739 if (first == null || toBeDel == null ) {
3840 return ;
3941 }
You can’t perform that action at this time.
0 commit comments