歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java實現簡單鏈表

Java實現簡單鏈表

日期:2017/3/1 10:21:04   编辑:Linux編程

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;
}
}

Copyright © Linux教程網 All Rights Reserved