双向链表的使用

双向链表中有一个头指针(head),然后每个节点有两个指针分别指向前面一个节点和后面一个节点。

​
package com.yf;



public class Day11 {
	public static void main(String[] args) {
		Node A = new Node(1,"yf1");
//		System.out.println();
		Node B = new Node(2,"yf2");
		Node C = new Node(3,"yf3");
		DoubleLinkedList list = new DoubleLinkedList();
//		list.addToEnd(C);
//		list.addToEnd(B);
//		list.addToEnd(A);
		list.addByOrder(C);
		list.addByOrder(B);
		list.addByOrder(A);

		list.showList();
		list.delete(1);
		list.showList();
		
	}
}

class Node{
	public int id;
	public String name;
	public Node pre;
	public Node next;
	public  Node(int id,String name) {
		this.id = id;
		this.name = name;
	}
	public String toString() {
		return "【id:"+id+"  name:"+name+"】";
	}
	
}

class DoubleLinkedList{
	private Node head = new Node(0,"");
	
	public void addToEnd(Node node) {
		Node temp = head;
		while(temp.next!=null) {
			temp = temp.next;
		}
		temp.next = node;
		node.pre = temp;
	}
	
	public void delete(int i) {
		Node temp = head.next;
		while(temp.next!=null && temp.id != i) {
			temp = temp.next;
		}
		if(temp.id == i) {
			temp.pre.next = temp.next;
			//如果删除的节点temp是最后一个节点,那么就不需要下面这一句话
			if(temp.next!=null) {
				temp.next.pre = temp.pre; 
			}
			
		}
		else {
			System.out.println("链表中没有这个节点");
		}
	}
	
	public void showList() {
		Node temp = head.next;
		while(temp!=null) {
			System.out.println(temp);
			temp = temp.next;
		}
	}
	
	public void addByOrder(Node node) {
		Node temp = head;
		while(temp.next!=null &&temp.next.id < node.id) {
			temp = temp.next;
		}
		
			
		if(temp.next != null ) {
			temp.next.pre = node;
			node.next = temp.next;
		}
			

		node.pre = temp;
		temp.next = node;
		
		
		
	}
}


​

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值