package com.important.data.struct.LinkedListDouble;
/*
* 双向链表实现
*/
public class MyLinkedList
{
public static void main(String[] args)
{
LinkedListType<String> linkedListType = new LinkedListType<>();
for(int i=1;i<6;i++){
String temp = i+"";
linkedListType.add(temp);
}
System.out.println("原始链表数据为: ");
linkedListType.println(linkedListType);
System.out.println("链表的大小为: ");
System.out.println(linkedListType.size());
linkedListType.set(2, "hha");
System.out.println("将链表的第二个位置重新设置后(修改)的链表为:");
linkedListType.println(linkedListType);
linkedListType.add(3, "xixi");
System.out.println("在链表的第三个位置添加节点后的链表为: ");
linkedListType.println(linkedListType);
// linkedListType.add(10, "x");
// linkedListType.println(linkedListType);
linkedListType.remove(4);
System.out.println("移除链表的第四个节点后的链表为: ");
linkedListType.println(linkedListType);
}
}
class LinkedListType<T>{
//用内部类来表示链表中的节点
private static class Node<T>{
public T date; //数据域
public Node<T> pre; //前指针
public Node<T> next; //后指针
public Node(T d,Node<T> p,Node<T> n){
date = d;
pre = p;
next = n;
}
}
private int theSize; //链表的大小
private Node<T> head; //双向链表的头指针
private Node<T> tail; //双向链表的尾指针
public LinkedListType()
{
clear();
}
//清空
public void clear(){
head = new Node<T>(null, null, null);
tail = new Node<T>(null,head,null); //尾指针的前指针指向头指针
head.next = tail; //头指针的后指针指向尾指针
theSize=0;
}
//大小
public int size(){
return theSize;
}
//判断是否为空
public boolean isEmpty(){
return size()==0;
}
//添加节点
public boolean add(T x){
add(size(), x);
return true;
}
public void add(int index,T x){
//要添加节点首选先获取要添加处的节点
Node<T> pNode = getNode(index);
addBefore(pNode, x);
}
public void addBefore(Node<T> pNode,T x){
Node<T> newNode = new Node<T>(x, null, null);
newNode.next = pNode;
newNode.pre = pNode.pre;
newNode.pre.next = newNode;
newNode.next.pre = newNode;
theSize++;
}
//取值
public T get(int index){
return getNode(index).date;
}
//设值
public T set(int index,T y){
Node<T> pNode = getNode(index);
T old = pNode.date;
pNode.date = y;
return old;
}
//移除结点
public T remove(int index){
Node<T> pNode = getNode(index);
return(remove(pNode));
}
public T remove(Node<T> pNode){
pNode.pre.next = pNode.next;
pNode.next.pre = pNode.pre;
pNode.pre = null;
pNode.next = null;
theSize--;
return pNode.date;
}
//获得节点
public Node<T> getNode(int index){
checkRange(index);
Node<T> pNode;
//前后遍历获取相应的节点
if(index<size()/2){
pNode = head.next;
for(int i=0;i<index;i++){
pNode = pNode.next;
}
}else {
pNode = tail;
for(int j=size();j>index;j--){
pNode = pNode.pre;
}
}
return pNode;
}
//检查index是否越界
public void checkRange(int index){
if (index<0 || index > size())
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size();
}
//输出
public void println(LinkedListType<T> linkedListType){
for(int i=0;i<linkedListType.size();i++){
System.out.print(linkedListType.get(i)+" ");
}
System.out.println();
}
}
双向链表(LinkedList) java实现
最新推荐文章于 2024-01-29 19:38:12 发布