在单链表中删除指定值的节点

来源:互联网 发布:淘宝和天猫哪个靠谱 编辑:程序博客网 时间:2024/05/21 15:02

import java.util.*;//在单链表中删除指定值的节点public class delNode{//节点的定义public static class Node{int value;Node next;public Node(int data){this.value=data;}}    //一、变量法存储public static Node DelNode(Node head,int num){if(head==null){return head;}//找到第一个不等于num的节点作为新的头结点while(head!=null){if(head.value!=num){break;}head=head.next;}Node pre=null;Node cur=head;while(cur!=null){if(cur.value==num) //删除节点cur{pre.next=cur.next;cur=cur.next;}else{pre=cur;cur=cur.next;}}return head;}    //二、用对列、栈方法存储    public static Node DelNode2(Node head,int num)    {    if(head==null){return head;}Stack<Node>stack=new Stack<Node>(); //栈存储//Queue<Node>queue=new LinkedList<Node>(); //队列存储while(head!=null){if(head.value!=num){stack.push(head);//queue.add(head);}head=head.next;}/*//获取队列第一个节点作为新的头结点        if(!queue.isEmpty())        {        System.out.println(queue.peek().value);        head=queue.poll();        }        Node q=head;//重新组成新的链表while(!queue.isEmpty()){System.out.println(queue.peek().value);q.next=queue.poll();q=q.next;}*/     //栈存储while(!stack.isEmpty()){stack.peek().next=head;head=stack.pop();}return head;    }    //打印链表    public static void PrintList(Node head){        while(head!=null)        {        System.out.print(head.value+" ");        head=head.next;        }        System.out.println();    }public static void main(String[]args){//System.out.println("Hello");Node node=new Node(1);node.next=new Node(2);        node.next.next=new Node(3);        node.next.next.next=new Node(4);        PrintList(node);        //Node mode=DelNode(node,1);        Node mode=DelNode2(node,1);        PrintList(mode);}}


原创粉丝点击