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

java使用泛型不使用任何库函数实现栈

2014-08-21 23:16 344 查看
有的笔试题需要不适用任何现成的数据结构实现stack或者queue,这是我写的一个简单的列子,只有入栈和出栈,希望对大家有帮助

package study;

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
* 使用泛型实现栈
* @author Shanys
*
* @param
*/
public class LinkedStack {
private Node head;
private static class Node{
U item;
Node[u] next;
public Node(){
item=null;
next=null;
}
public Node(U item,Node[u] next){
this.item=item;
this.next=next;
}
}
public void push(T item){
//头插法,链表的思想实现栈
Node node = new Node();
node.item=item;
if(head.next==null){
head.next=node;
}else{
node.next=head.next;
head.next=node;
}
}
public T pop(){
T item = null;
if(head.next!=null){
Node node = head.next;
item = node.item;
head.next=node.next;
node = null;
}
return item;
}
public LinkedStack(){
head = new Node();
}
public static void main(String[] args) {
LinkedStack t = new LinkedStack();
for(String s : "this is a test".split(" ")){
System.out.println(s);
t.push(s);
}

String temp;System.out.println("hello");
while((temp = t.pop())!=null){
System.out.println(temp);
}
}
}
[/u][/u]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: