程序小白,希望和大家多交流,共同学习
范类型,实现链表。
import java.util.Scanner;
//使用泛型实现所有类型的栈
public class GenericLinkedList<E>{
//定义泛型的结点
private static class MyNode<E>{
private E element;
private MyNode next;
public MyNode(){
}
public MyNode(E e){
this.element = e;
}
}
//链表的数据
private MyNode head;
public GenericLinkedList(){
head = new MyNode<>();
head = null;
}
public MyNode getHead(){
return head;
}
public int push(E e){
if (isFull()){
System.out.println("此栈已满,无法实现入栈");
return -1;
}
else{
MyNode<E> node = new MyNode<>();
node.element = e;
node.next = head;
head = node;
return 0;
}
}
public boolean isFull(){
MyNode<E> node = new MyNode<>();
if (node == null){
return true;
}
else
return false;
}
public Object getTop(){//这里不能使用E因为head.element 是Object对象
if (isEmpty()){
System.out.println("此栈已空,没有栈顶元素");
return null;
}
else
return head.element;
}
public boolean isEmpty(){
return head == null;
}
public int pop(){
if (isEmpty()){
System.out.println("此栈已空,无法出栈");
return -1;
}
else{
head = head.next;
return 0;
}
}
@Override
public String toString(){
StringBuilder result = new StringBuilder("[");
MyNode<E> head = getHead();
while (head != null){
result.append(head.element);
if (head.next != null){
result.append(", ");
}
head = head.next;
}
result.append("]");
return result.toString();
}
}
import java.util.Scanner;
public class TestGenericLinkedList{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
GenericLinkedList<Integer> linkedList = new GenericLinkedList<>();
int num;
System.out.println("输入数据进栈:");
while (true){
num = input.nextInt();
if (num == -1){
break;
}
else
{
linkedList.push(new Integer(num));
}
}
System.out.println(linkedList.toString());
while (!linkedList.isEmpty()){
System.out.println(linkedList.getTop());
linkedList.pop();
System.out.println(linkedList.toString());
}
}
}