本文实例为大家分享了Java 8实现任意参数的单链表,供大家参考,具体内容如下
1、实现功能
1)add():链表末尾添加元素;
2)pop():移除链表尾部元素;
3)insert():指定索引处添加元素;
4)delete():指定索引处删除元素;
5)getSize():获取链表当前长度;
6)display():展示链表当前元素。
2、代码
package DataStructure;
public class MySinglelinkedList {
private SingleNode head = new SingleNode(new Object());
private int size = 0;
public void add(AnyType paraVal) {
insert(size, paraVal);
}//Of add
public AnyType pop(){
return delete(size - 1);
}//Of pop
public void insert(int paraIdx, AnyType paraVal) {
if (paraIdx > size) {
throw new IndexOutOfBoundsException("The index error.");
}//Of if
SingleNode tempNode = head;
int i = 0;
while (i++ < paraIdx) {
tempNode = tempNode.next;
}//Of while
SingleNode paraNode = new SingleNode <>(paraVal);
paraNode.next = tempNode.next;
tempNode.next = paraNode;
size++;
}//of add
public AnyType delete(int paraIdx) {
if (size == 0) {
throw new RuntimeException("The single linked list is empty.");
}//Of if
if (size <= paraIdx) {
throw new IndexOutOfBoundsException("The index error.");
}//Of if
SingleNode retNode = head;
int i = 0;
while (i++ < paraIdx) {
retNode = retNode.next;
}//Of while
retNode.next = retNode.next.next;
size--;
return retNode.val;
}//Of delete
public int getSize() {
return size;
}//Of getSize
public void display() {
if (size == 0) {
throw new RuntimeException("The single linked list is empty.");
}//Of if
System.out.print("The single linked list is:n[");
SingleNode tempNode = head;
int i = 0;
while (i++ < size - 1) {
tempNode = tempNode.next;
System.out.printf("%s, ", tempNode.val);
}//Of while
System.out.printf("%s]n", tempNode.next.val);
}//Of display
public static void main(String[] args) {
MySinglelinkedList test = new MySinglelinkedList<>();
test.add('a');
test.add('b');
test.insert(0, 'c');
test.add('d');
test.insert(0, '5');
test.delete(4);
test.pop();
test.add('+');
test.display();
System.out.println(test.getSize());
}//Of main
}//Of class MySinglelinkedList
class SingleNode {
AnyType val;
SingleNode next;
SingleNode (AnyType paraVal) {
val = paraVal;
}//The first constructor
}//Of class SingleNode
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



