您的位置:首页 > 编程语言 > Java开发

用java实现的自定义单向链表

2015-09-25 09:37 513 查看
package com.hebtu.java.list;

/**
* 链表节点
* @author Xmh
*
*/
public class Link {
private int num;

private Link next; //指向下一个节点

public Link() {
super();
}

public Link(int num) {
super();
this.num = num;
}

public void displayLink(){
System.out.println("num: " + num);
}

public int getNum() {
return num;
}

public void setNum(int num) {
this.num = num;
}

public Link getNext() {
return next;
}

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

public static void main(String[] args) {
MyList list = new MyList();
//插入数据
list.insert(2);
list.insert(4);
list.insert(6);
list.insert(8);
//打印链表
list.displayList();

//链表不为空,删除数据
while(!list.isEmpty()){
Link removeFirst = list.removeFirst();
System.out.println("Delete....");
removeFirst.displayLink();
}

list.displayList();
}
}

/**
* MyList: 自定义的单向链表,支持表头插入和表头删除操作
* @author Xmh
*
*/
class MyList{
private Link first; //指向第一个节点对象的引用

/**
* 构造器:初始化空链表,让 first引用指向 null(默认就是指向 null 的)
*/
public MyList() {
first = null;
}

/**
* 往链表中插入数据:只在表头插入
* @param num
*/
public void insert(int num){
// 1.先创建一个节点对象
Link newLink = new Link(num);
// 2.1 新对象 的 next 引用,指向 first
newLink.setNext(first);
// 2.2 让first指向新插入的对象
first = newLink;
}

/**
* 从链表中移除头结点,并且返回之。
* @return
*/
public Link removeFirst(){
Link temp = first; //首先保存第一个节点的引用,即要输出的节点
// first--->old next(将first引用指向下下个节点对象)
first = first.getNext();
return temp;
}

/**
* 打印链表
*/
public void displayList(){
System.out.println("List(first--->last)...");
Link current = first; // 链表的开始节点引用
while(current != null){
current.displayLink();
//指向下一个节点
current = current.getNext();
}
System.out.println("");
}

/**
* 判断链表是否为空
* @return
*/
public boolean isEmpty(){
if(first==null){
return true;
}else{
return false;
}
}

}
控制台打印结果:
List(first--->last)...
num: 8
num: 6
num: 4
num: 2

Delete....
num: 8
Delete....
num: 6
Delete....
num: 4
Delete....
num: 2
List(first--->last)...


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