总结一下前一段时间的学习java容器的进展。
代码中没有添加异常处理。
单链表:
class Node{
private Object data;
private Node next;
private Node temp = null;
public Node(Object data){
this.data = data;
}
public Node(){
}
//添加元素,时间复杂度为O(1)
public void addElement(Object obj){
Node node = new Node(obj);
node.next = temp;
temp = node;
}
//移除元素,时间复杂度为O(n)
public void removeElement(Object obj){
if(temp.data.equals(obj)){
temp = temp.next;
}else{
Node pre = temp;
Node cur = temp.next;
while(cur != null){
if(cur.data.equals(obj)){
pre.next = cur.next;
}else{
pre = cur;
cur = cur.next;
}
}
}
}
//遍历输出元素
public void display(){
Node cur = temp;
while(cur != null){
System.out.print(cur.data + "->");
cur = cur.next;
}
System.out.print("\n");
}
}
双向链表:
class DoubleLinkNode{
private Object data;
priavte DoubleLinkNode pre;
private DoubleLinkNode next;
private DoubleLinkNode temp;
public DoubleLinkNode(){
}
public DoubleLinkNode(Object data){
this.data = data;
}
public boolean isEmpty(){
return (temp == null);
}
//头插法插入元素
public void addElementHead(Object obj){
DoubleLinkNode node = new DoubleLinkNode(obj);
if(isEmpty()){
node.pre = null;
node.next = null;
}else{
node.next = temp;
temp.pre = node;
}
temp = node;
}
//遍历输出元素
public void displayHead(){
Node cur = temp;
while(cur != null){
System.out.print(cur.data + "->");
cur = cur.next;
}
System.out.print("\n");
}
//尾插法插入元素
public void addElementTail(Object obj){
if(isEmpty()){
node.pre = null;
node.next = null;
}else{
node.pre = temp;
temp.next = node;
}
temp = node;
}
//遍历输出元素
public void displayTail(){
Node cur = temp;
while(cur != null){
System.out.print(cur.data + "->");
cur = cur.pre;
}
System.out.print("\n");
}
}
循环链表:
class LoopNode{
private Object data;
private LoopNode next;
private LoopNode head;
private LoopNode temp = null;
public LoopNode(){}
public LooopNode(Obejct data){
this.data = data;
}
//插入元素
public void addElement(Object obj){
LoopNode node = new LoopNode(obj);
if(isEmpty()){
head = node;
temp = node;
head.next =head;
}else{
temp.next = node;
node.next = head;
temp = node;
}
}
//遍历
public void display(){
LoopNode cur = head;
while(cur != null){
System.out.print(cur.data+"->");
cur = cur.next;
}
System.out.print("\n");
}
public boolean isEmpty(){
return (temp == null)
}
}