java 单向链表的操作
今天复习了一下数据结构,参考了网上的一个例子,自己写了个单向链表的操作。以下附上代码供大家参考:
/**
* 链表节点
* @author yangchuxi
*
*/
public class Node<Object> {
public Object t;
public Node<Object> next;
public Node(Object t){
this.t=t;
}
public String toString(){
return t.toString();
}
/**
* 单向链表的操作类
* @author yangchuxi
*
*/
public class SingleList {
private Node<Object> head;
private int size;
//链表的初始化
public SingleList() {
size=0;
//表头不放数据
head=new Node<Object>(null);
head.next=null;
}
//插入到链表前段(表头之后)
public void insertfirst(Node<Object> n){
n.next=head.next;
head.next=n;
size++;
}
//插入到链表的末尾
public void insertlast(Node<Object> n){
n.next=null;
Node<Object> p=head;
while(p.next!=null){
p=p.next;
}
p.next=n;
size++;
}
// 在指定节点后添加节点
public void insertinto(Node<Object> n1,Node<Object> n2){
n2.next=n1.next;
n1.next=n2;
size++;
}
删除链表前端节点
public void deletehead(){
Node<Object> current =head.next;
head.next=current.next;
current=null;
size--;
}
删除尾节点
public void deletetail(){
Node<Object> current =head;
Node<Object> pre=null;
while(current.next!=null){
pre=current;
current=current.next;
}
current=null;
pre.next=null;
size--;
}
// 删除指定节点
public boolean deltete(Node<Object> n){
if(n!=null){
if(head.next!=null &&n==head.next){
deletehead();
return true;
}
//获得末端节点
Node<Object> tail=head;
while(tail.next!=null){
tail=tail.next;
}
if(n==tail){
deletetail();
return true;
}
Node<Object> current=head;
Node<Object> pre=null;
if(current!=null && current!=n){
current=current.next;
while(current.next.next!=null){
pre=current;
current=current.next;
}
pre.next=current.next;
current=null;
return true;
}
}
System.out.println("delete false...........");
return false;
}
// 链表长度
public int getSize() {
return size;
}
// 遍历链表并打印
public void diplay() {
Node<Object> current = head.next;
while (current != null) {
System.out.println(current.toString());
current = current.next;
}
}
public static void main(String[] args) {
//测试链表的操作是否正确
SingleList singleList=new SingleList();
Node node1=new Node<Object>("testlist1");
Node node2=new Node<Object>("testlist2");
Node node3=new Node<Object>("testlist3");
Node node4=new Node<Object>("testlist4");
singleList.insertfirst(node1);
singleList.insertfirst(node2);
singleList.insertinto(node2, node3);
singleList.insertlast(node4);
singleList.diplay();
//singleList.deletehead();
//singleList.diplay();
//singleList.deletetail();
//singleList.diplay();
//singleList.deltete(node1);
//singleList.diplay();
//singleList.deltete(node2);
//singleList.diplay();
singleList.deltete(node4);
singleList.diplay();
}
}