王元浩


私信TA

用户名:dotcpp0664606

访问量:1988

签 名:

等  级
排  名 458
经  验 4623
参赛次数 1
文章发表 40
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

TA的其他文章

解题思路:

双向链表实现链表删除;

在添加操作时比单链表多了一个指向前面的元素的操作;

删除比单链表方便,这时的删除是直接指向当前要删除的元素,多了temp.pre.next=tem.next;temp.next.pre=temp.pre,但最后这个要防止空指针异常



注意事项:

求助!!!有两个运行超时,怎么优化??

参考代码:

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       int n=scanner.nextInt();
     DoubleLinkedList doubleLinkedList=new DoubleLinkedList();
       for (int i=1;i<=n;i++){
         int a=scanner.nextInt();
           Node node=new Node(a);
           doubleLinkedList.add(node);
       }
       int b=scanner.nextInt();
       for(int i=0;i<n;i++)
       {
           doubleLinkedList.delete(b);
       }
       doubleLinkedList.list();





   }
}
class  DoubleLinkedList{
   private Node head=new Node(-1);
   //添加操作,切记连接双向链表
   public void add(Node node){
       Node temp=head;
       while (true){
           if (temp.next==null){
               break;
           }
           temp=temp.next;
       }
       temp.next=node;
       node.pre=temp;
   }
   public void delete(int no){
       if (head.next==null){
           //表明链表为空
           return;
       }
       Node temp=head.next;
       boolean flag=false;
       while (true){
           if (temp==null){
               break;
               //表明到尾部了
           }
           if (temp.no==no){
               flag=true;
               break;
           }
           temp=temp.next;
       }
       if (flag){
           temp.pre.next=temp.next;
           if (temp.next!=null){
               temp.next.pre=temp.pre;
           }
       }

   }
   //显示链表【遍历】
   public void list() {
       //判断链表为空
       if (head.next == null) {
           System.out.println("链表为空");
           return;
       }

       Node temp = head.next;
       while (true) {
         
           if (temp == null) {
               break;
           }
           //输出节点的信息
           System.out.print(temp+"");
           //将next后移
           temp = temp.next;
       }
   }

   }
   

class Node{
   public int no;
   public Node next;
   public  Node pre;

   public Node(int no) {
       this.no = no;
   }

   @Override
   public String toString() {
       return
              no +" ";
   }
}

 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区