转载请标明出处http://www.cnblogs.com/haozhengfei/p/5155a3f1ce0612e35ec202156921836f.html 


链表指定值清除

算法--链表指定值清除
算法--链表指定值清除
算法--链表指定值清除
 
 

第8节 链表指定值清除练习题

 

现在有一个单链表。链表中每个节点保存一个整数,再给定一个值val,把所有等于val的节点删掉。

给定一个单链表的头结点head,同时给定一个值val,请返回清除后的链表的头结点,保证链表中有不等于该值的其它值。请保证其他元素的相对顺序。

测试样例:
{1,2,3,4,3,2,1},2
{1,3,4,3,1}
Java (javac 1.7)
 
 
1
import java.util.*;
2

3
/*
4
public class ListNode {
5
    int val;
6
    ListNode next = null;
7

8
    ListNode(int val) {
9
        this.val = val;
10
    }
11
}*/
12
public class ClearValue {
13
    public ListNode clear(ListNode head, int val) {
14
        while (head != null) {
15
            if (head.val != val) {
16
                break;
17
            }
18
            head = head.next;
19
        }
20
        ListNode pre = head;
21
        ListNode cur = head;
22
        while (cur != null) {
23
            if (cur.val == val) {
24
                pre.next = cur.next;
25
            } else {
26
                pre = cur;
27
            }
28
            cur = cur.next;
29
        }
30
        return head;
31
    }
32
}
 
 
您的代码已保存
答案正确:恭喜!您提交的程序通过了所有的测试用例
 
 
算法--链表指定值清除
 
 

相关文章:

  • 2021-06-09
  • 2021-05-31
  • 2021-07-15
  • 2021-11-11
  • 2022-12-23
  • 2021-10-21
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-16
相关资源
相似解决方案