一、说一下双端链表
1、关于链表
https://blog.csdn.net/qq_38401906/article/details/83715163
2、双端链表
链表中同不仅含有头节点的引用,也包含尾节点的引用,即可以从尾部插入数据。
二、用java实现双端链表的增删操作
节点:
package myStudy.dataStructure.day2;
/**
*
* @description 节点类
* @author shenrenfeng
* @date 2018年11月4日 上午11:14:07
*
*/
public class Node {
private int data;// 节点数据
private Node next;// 节点指针,指向下一个节点
public Node(int data) {
this.data = data;
this.next = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
双端链表:
package myStudy.dataStructure.day5;
import myStudy.dataStructure.day2.Node;
/**
*
* @description 双端链表(有头有尾)
* @author shenrenfeng
* @date 2018年11月7日 下午8:14:07
*
*/
public class DoubleEndLinkedList {
private Node head;// 头节点
private Node tail;// 尾节点
/**
* 从头节点之后插入
* @param Data
*/
public void insertFromHead(int data) {
Node node = new Node(data);
if(head == null) {// 如果头节点为空,那么插入的数据为头节点同时也是尾节点
head = node;
tail = node;
} else {
if(head.getNext() == null) {// 如果当前只有一个节点,新插入的节点为尾节点
tail = node;
}
node.setNext(head.getNext());
head.setNext(node);
}
}
/**
* 从尾节点之后插入
* @param data
*/
public void insertFromTail(int data) {
Node node = new Node(data);
if(head == null) {
head = node;
} else {
tail.setNext(node);
}
tail = node;
}
/**
* 从头节点删除
* @return
*/
public Node deleteFromHead() {
Node deleteNode = head;
if(head != null) {
head = head.getNext();
}
return deleteNode;
}
/**
* 展示数据
*/
public void showList() {
Node node = head;
while(node != null) {
System.out.print(node.getData());
System.out.print(" ");
node = node.getNext();
}
}
}
测试:
package myStudy.dataStructure.day5;
/**
*
* @description
* @author shenrenfeng
* @date 2018年11月7日 下午8:40:42
*
*/
public class Test {
public static void main(String[] args) {
DoubleEndLinkedList linkedList = new DoubleEndLinkedList();
linkedList.insertFromHead(0);
linkedList.insertFromHead(1);
linkedList.insertFromHead(2);
linkedList.insertFromTail(3);
linkedList.insertFromTail(4);
linkedList.insertFromTail(5);
linkedList.showList();
System.out.println();
System.out.println(linkedList.deleteFromHead().getData());
System.out.println(linkedList.deleteFromHead().getData());
System.out.println(linkedList.deleteFromHead().getData());
linkedList.showList();
}
}
结果: