您的位置:首页 > 理论基础 > 数据结构算法

数据结构之链表

2016-09-27 12:43 369 查看

数据结构之链表

数据结构中,链表算是简单的一种。今天就来写一下链表的原理与实现

github传送门

简介

链表为啥叫链表。因为他就和一个链子一样。链表分为

单向链表

双向链表

循环链表

实现

双向链表

为什么只讲双向链表呢。我用一张图给大家诠释



可以看出来 单向链表只是存有下个节点的引用,双向列表是存有他上个节点和下个节点的引用,循环链表是他每个节点都存有他的上个节点的引用和下个节点的引用,这里要注意的是,他们开始的时候都要有个头节点,里面不存数据,只存首节点的数据。

首先来写节点

public class Node {
private String date;
private Node next;
private Node previous;

public Node() {
}

public Node(String date) {
this.date = date;
}

//省略get和set方法

@Override
public String toString() {
System.out.print(date);
return date;
}

public boolean equals(Node obj) {
if(date.equals(obj.getDate())){
return true;
}else {
return false;
}
}
}


这里面next存着下个节点,previous存着上一个节点

然后写一个抽象类,定义list的操作

abstract  class  ListAbs {
abstract void add(Node node);
abstract void remove(Node node);
abstract Node get(int position);
}


这里面我们只实现 增加 删除 和得到下标的Node

这里是实现

public class LinkedList extends ListAbs {

private Node headNode;
private Node lastNode;
private int size=0;
//    private java.util.LinkedList

public LinkedList(){
headNode=new Node();
}

void add(Node node){
if(node!=null){
if(lastNode==null) {
//如果是插入的第一个节点
headNode.setNext(node);
node.setPrevious(headNode);
}else{
//如果是插入的不是第一个节点
lastNode.setNext(node);
node.setPrevious(lastNode);
}
lastNode=node;
size++;
}else{
throw new NullPointerException("插入节点为空!");
}
}

void remove(Node node){
/*移除这个节点就是把这个节点的上一个节点与这个节点的下个节点链接起来 */
if(node!=null){
Node next=node.getNext();
Node pre=node.getPrevious();

pre.setNext(next);
next.setPrevious(pre);

size--;
}else{
throw new NullPointerException("删除节点为空!");
}

}

Node get(int position) {
checkElement(position);
int x=0;
for(Node n=headNode.getNext();;n= n.getNext()){
if(position==x){
return  n;
}else{
x++;
}
}
}

//检测是否超出了长度
protected void checkElement(int position){
if(position>=size){
throw new IndexOutOfBoundsException("超出link的大小");
}
}

@Override
public String toString() {
StringBuffer linked=new StringBuffer();
Node next=headNode.getNext();
while(next!=null){
linked.append(next.getDate()+"--->");
next=next.getNext();
}
return linked.toString();
}
}


上面写的我感觉大家应该都能看懂,如果有哪里不理解的可以直接评论。

差点忘了测试的代码。。。

public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.add(new Node("Node_1"));
linkedList.add(new Node("Node_2"));
linkedList.add(new Node("Node_3"));
linkedList.add(new Node("Node_4"));
linkedList.add(new Node("Node_5"));
System.out.printf(linkedList.toString()+"\n\n");

linkedList.remove(linkedList.get(2));
System.out.printf(linkedList.toString());
}


执行之后输入的结果为

Node_1--->Node_2--->Node_3--->Node_4--->Node_5--->

Node_1--->Node_2--->Node_4--->Node_5--->
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: