public class TestLinkList {
public static void main(String [] args){
LinkList<String>list = new LinkList<String>();
list.insert("aaaa", 0);
list.addTail("bbbb");
list.addTail("cccc");
System.out.print("原始的链表:");
list.traverse();
list.insert("dddd" , 1);
System.out.print("添加元素之后的链表:");
list.traverse();
list.delete(2);
System.out.print("删除元素之后的链表:");
list.traverse();
System.out.println("cccc在链表中的位置:"
+ list.getIndex("cccc"));
System.out.println("链表中索引2处的元素:"
+ list.getNode(2).data);
}
}
class LinkList<T>{
class Node{
public T data;
public Node next;
public Node(T data,Node next){
this.data = data;
this.next = next;
}
}
private Node header;
private Node tail;
private int size;
public LinkList(){
header = null;
tail = null;
}
public int length(){
return size;
}
public void traverse(){
for(Node tempNode=header;tempNode!=null;tempNode=tempNode.next){
System.out.printf("%s ", tempNode.data.toString());
}
System.out.println();
}
public Node getNode(int index){
if(index < 0 || index > size - 1){
System.out.println("位置非法");
}
Node tempNode = header;
for(int i=0;i<size;i++){
if(tempNode == null){
break;
}
if(i == index){
return tempNode;
}
tempNode = tempNode.next;
}
return null;
}
public int getIndex(T element){
Node tempNode = header;
if(tempNode != null){
for(int i=0;i<size;i++){
if(tempNode.data.equals(element)){
return i;
}
tempNode = tempNode.next;
}
}
return -1;
}
public void addTail(T element){
if(header == null){
header = new Node(element,null);
tail = header;
}
else{
Node newNode = new Node(element,null);
tail.next = newNode;
tail = newNode;
}
size++;
}
public void addHeader(T element){
if(tail == null){
tail = new Node(element,null);
header = tail;
}
else{
Node newNode = new Node(element,header);
header = newNode;
}
size++;
}
public void insert(T element,int index){
if(index < 0 || index > size){
System.out.println("位置非法");
}
if(header == null){
addTail(element);
}
else{
if(index == 0){
addHeader(element);
}
else{
Node pre = getNode(index-1);
pre.next = new Node(element,pre.next);
size++;
}
}
}
public T delete(int index){
if(index < 0 || index > size - 1){
System.out.println("位置非法");
}
Node del = null;
if(index == 0){
del = header;
header = header.next;
}
else{
Node pre = getNode(index - 1);
del = pre.next;
pre.next = del.next;
del.next = null;
}
size--;
return del.data;
}
public boolean empty(){
return size == 0;
}
public void clear(){
header = null;
tail = null;
size = 0;
}
}
Java数据结构之单向链表
最新推荐文章于 2021-05-23 22:47:42 发布