解题思路:
双向链表实现链表删除;
在添加操作时比单链表多了一个指向前面的元素的操作;
删除比单链表方便,这时的删除是直接指向当前要删除的元素,多了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 人评分
C语言程序设计教程(第三版)课后习题1.6 (C语言代码)浏览:584 |
程序员的表白 (C语言代码)浏览:666 |
WU-整数平均值 (C++代码)浏览:1244 |
C语言程序设计教程(第三版)课后习题6.5 (C++代码)浏览:457 |
C语言程序设计教程(第三版)课后习题6.1 (C语言代码)浏览:701 |
【计算两点间的距离】 (C语言代码)浏览:1493 |
C语言程序设计教程(第三版)课后习题3.7 (C语言代码)浏览:704 |
C语言程序设计教程(第三版)课后习题10.2 (C语言代码)浏览:687 |
众数问题 (C语言代码)浏览:673 |
C语言程序设计教程(第三版)课后习题5.4 (C语言代码)浏览:458 |