java实现单双向链表

public class Node {
private Object data;
private Node next;

public Node(Object data, Node next) {
super();
this.data = data;
this.next = next;
}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

public Node getNext() {
return next;
}

public void setNext(Node next) {
this.next = next;
}
}

public class LinkedList {
private Node head;
private Node tail;
private int size;

public void add(Object obj) {
Node node = new Node(obj, null);
if (head == null) {
head = node;
tail = node;
}
tail.setNext(node);
tail = node;
size++;
}

public int size() {
return size;
}
}

junit test code:
@Test
public void testAdd() {
LinkedList linkedList = new LinkedList();
for (int i = 0; i < 15; i++) {
linkedList.add(new Cat(i));
}
assertTrue(linkedList.size()==15);
}


public class LinkNode {
private Object data;
private LinkNode right;
private LinkNode left;

public LinkNode(Object data, LinkNode right, LinkNode left) {
super();
this.data = data;
this.right = right;
this.left = left;
}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

public LinkNode getRight() {
return right;
}

public void setRight(LinkNode right) {
this.right = right;
}

public LinkNode getLeft() {
return left;
}

public void setLeft(LinkNode left) {
this.left = left;
}
}

public class Link {
private LinkNode head;
private LinkNode tail;
private int size;

public void add(Object obj) {
LinkNode node = new LinkNode(obj, null, null);
if (head == null) {
head = node;
tail = head;
head.setRight(tail);
head.setLeft(tail);
}
tail.setRight(node);
node.setLeft(tail);
tail = node;
tail.setRight(head);
head.setLeft(tail);
size++;
}

public int size() {
return size;
}

public LinkNode getTailNode() {
return tail;
}

public LinkNode getHeadNode() {
return head;
}
}

junit test code:
@Test
public void testAdd() {
Link link = new Link();
for (int i = 0; i < 15; i++) {
link.add(new Cat(i));
}
assertTrue(link.size()==15);

assertEquals(link.getHeadNode().getLeft().getData(),link.getTailNode().getData());
assertEquals(link.getTailNode().getRight().getData(),link.getHeadNode().getData());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值