【題目】
給定一個鏈表的頭節點head和一個整數num,請實現函數將值爲num的節點全部刪除
【代碼1】
時間複雜度O(n),空間複雜度O(n)
class Solution {
public ListNode deleteNode(ListNode head, int val) {
ListNode cur = head;
Stack<ListNode> stack = new Stack<>();
while(cur != null){
if(cur.val != val){
stack.push(cur);
}
cur = cur.next;
}
while(!stack.isEmpty()){
stack.peek().next = cur;
cur = stack.pop();
}
return cur;
}
}
【代碼2】
時間複雜度O(n),空間複雜度O(1)
class Solution {
public ListNode deleteNode(ListNode head, int val) {
while(head != null){
if(head.val != val){
break;
}
head = head.next;
}
ListNode cur = head;
ListNode pre = head;
while(cur != null){
if(cur.val == val){
pre.next = cur.next;
}else{
pre = cur;
}
cur = cur.next;
}
return head;
}
}