題目
給定一個鏈表的頭節點head和一個整數num,實現函數將值爲num的節點全部刪除。
原鏈表 | 刪除後鏈表 |
1->2->3->4->null, num=3 | 1->2->4->nulll |
思路
方法一:利用棧,時空複雜度均爲O(N)
- 將值不等於num的節點按鏈表順序壓棧
- 遍歷完鏈表再依次彈棧,重新連接即可。
源碼
public class Node{
public int value;
public Node next;
public Node(int data){
this.value=data;
}
}
public 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;
}