删除链表中指定节点
思路:利用其他结构(这里利用栈结构)存放链表中除要删除的节点外的其他节点。依次将链表元素放入栈中,当遇到要删除的元素时跳过,最后将栈中元素重新连接成链表。
具体代码
public class removeValue {
public static class Node{
public int val;
public Node next;
public Node(int val){
this.val = val;
}
}
public static Node remove(Node head,int num){
Stack<Node> stack = new Stack<>();
while(head != null){
if(head.val != num){
stack.push(head);
}
head = head.next;
}
//将栈中元素重新连接成链表
while(!stack.isEmpty()){
//将栈中元素从栈顶依次指向上面,刚开始栈顶元素指向空,栈底元素成为链表头节点
stack.peek().next = head;
head = stack.pop();
}
return head;
}
public static void print(Node head){
if(head==null){
return ;
}
while(head != null){
System.out.print(head.val+" ");
head = head.next;
}
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
Node node = remove(head, 3);
print(node);
}
}
测试结果