7.2:链表删除给定值

7.2:链表删除给定值

 

 1 // head = removeValue(head, 2);
 2     public static Node removeValue(Node head, int num) {
 3         // head来到第一个不需要删的位置
 4         while (head != null) {
 5             if (head.value != num) {       //找到第一个不需要删除的节点作为头部返回
 6                 break;
 7             }
 8             head = head.next;
 9         }
10         // 1 ) head == null   全删除了后为null
11         // 2 ) head != null
12         Node pre = head;
13         Node cur = head;
14         while (cur != null) {
15             if (cur.value == num) {           //cur值是要删除的值 
16                 pre.next = cur.next;          //pre指向cur的后一个
17             } else {
18                 pre = cur;                    //cur值不是要删除的值。pre随着cur移动
19             }
20             cur = cur.next;                  //cur逐个往后走
21         }
22         return head;
23     }

 

 

posted @ 2022-05-06 18:43  yzmarcus  阅读(34)  评论(0编辑  收藏  举报