设为首页 加入收藏

TOP

Java实现简单链表
2014-11-24 12:31:37 】 浏览:2596
Tags:Java 实现 简单

Java实现简单链表


package com.zte.test;


public class main {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
OperaNode op = new OperaNode();
op.addToHead(1);
op.addToHead(2);
op.addToTail(3);
op.addToHead(5);
op.printAll();


}


}


class Node {
public int size;
public Node next;


public Node(int i) {
this(i, null);
}


public Node(int i, Node n) {
size = i;
next = n;
}
}


class OperaNode {
private Node head, tail;


public OperaNode() {
head = tail = null;
}


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


/**
* 在链表的头部添加数据
*
* @param l
*/
public void addToHead(int l) {
head = new Node(l, head);
if (tail == null) {
tail = head;
}
}


/**
* 在链表的尾部添加数据
*
* @param l
*/
public void addToTail(int l) {
if (!isEntry()) {
tail.next = new Node(l);
tail = tail.next;
} else {
head = tail = new Node(l);
}
}


/**
* 删除链表头部数据
*/
public int deleteToHead() {
int el=head.size;
if (head == tail) {
head = tail = null;
} else {
head = head.next;
}
return el;
}


/**
* 删除链表最后一个数据
*/
public int deleteToTail() {
int el = tail.size;
if (head == tail) {
head = tail = null;
} else {
Node temp;
for (temp = head; temp.next != tail; temp = temp.next)
;
tail = temp;
tail.next = null;
}
return el;
}


/**
* 打印链表中所有的数据
*/
public void printAll() {
Node temp;
for (temp = head; temp != null ; temp = temp.next) {
System.out.println(temp.size);
}
}


/**
* 删除链表中I的值
*
* @param i
*/
public void delete(int i) {
if (!isEntry()) {
if (head == tail && i == head.size) {
head = tail = null;
} else if (i == head.size) {
head = head.next;
}
} else {
Node pred, tmp;
for (pred = head, tmp = head.next; tmp != null && tmp.size != i; pred = pred.next, tmp = tmp.next)
;
if (tmp != null) {
pred.next = tmp.next;
if (tmp == tail) {
tail = pred;
}
}
}
}


/**
* 用于判断链表中是否有这个值
*
* @param el
* @return
*/
public boolean isIntList(int el) {
Node tmp;
for (tmp = head; tmp != null && tmp.size != el; tmp = tmp.next)
;
return tmp != null;
}
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Android存储——SharedPreference.. 下一篇Android代码控制seekbar的样式

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目