【题目】给定一个链表的头节点head和一个整数num,请实现函数将值为num的节点全部删除。
例如,链表为1->2->3->4->null,num = 3,链表调整后为:1->2->4->null。
public class RemoveValNode {
public static class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
// 时间复杂度O(N),空间复杂度O(N)
public static Node removeValue1(Node head, int num) {
Stack<Node> stack = new Stack<Node>();
while (head != null) {
if (head.value != num) {
stack.push(head);
}
head = head.next;
}
while (!stack.isEmpty()) {
stack.peek().next = head;
head = stack.pop();
}
return head;
}
// 时间复杂度O(N),空间复杂度O(1)
public static Node removeValue2(Node head, int num) {
while (head != null) {
if (head.value != num) {
break;
}
head = head.next;
}
Node pre = head;
Node cur = head;
while (cur != null) {
if (cur.value == num) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return head;
}
}