循环链表的经典实现(JAVA)


public class LinkedListNode {//链表节点

public LinkedListNode previous;//前一节点
public LinkedListNode next;//后一节点
public Object object;//节点中存的值


public long timestamp;


public LinkedListNode(Object object, LinkedListNode next, LinkedListNode previous)
{
this.object = object;
this.next = next;
this.previous = previous;
}


public void remove() {//删除自己
previous.next = next;
next.previous = previous;
}


public String toString() {
return object.toString();
}
}

import java.util.*;


public class LinkedList {//循环链表

//头指针,哑的,第一个节点的前面,最后一个节点的后面
private LinkedListNode head = new LinkedListNode("head", null, null);


public LinkedList() {
head.next = head.previous = head;
}


public LinkedListNode getFirst() {//获取循环链表的第一个节点
LinkedListNode node = head.next;
if (node == head) {
return null;
}
return node;
}


public LinkedListNode getLast() {//获取循环链表的最后一个节点
LinkedListNode node = head.previous;
if (node == head) {
return null;
}
return node;
}


public LinkedListNode addFirst(LinkedListNode node) {//将节点插入到链表的第一个位置,头节点之后.
node.next = head.next;
node.previous = head;
node.previous.next = node;
node.next.previous = node;
return node;
}


public LinkedListNode addFirst(Object object) {//将值插入到链表的第一个位置,头节点之后.
LinkedListNode node = new LinkedListNode(object, head.next, head);
node.previous.next = node;
node.next.previous = node;
return node;
}

public LinkedListNode addLast(Object object) {//将值插入到链表的最后一个位置,头节点之前
LinkedListNode node = new LinkedListNode(object, head, head.previous);
node.previous.next = node;
node.next.previous = node;
return node;
}


public void clear() {//清空循环链表
//Remove all references in the list.
LinkedListNode node = getLast();
while (node != null) {
node.remove();
node = getLast();
}

//Re-initialize.
head.next = head.previous = head;
}

public String toString() {
LinkedListNode node = head.next;
StringBuffer buf = new StringBuffer();
while (node != head) {
buf.append(node.toString()).append(", ");
node = node.next;
}
return buf.toString();
}
}




源码:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值