package com.beihang;import java.util.Hashtable;public class MyLinkList { Node head=null;//链表头的引用

//添加新节点 d为插入的数据
public void addNode(int d){
Node newNode=new Node(d);
if(head==null){
//判断起始点是否为空,若为空则把新结点赋给head
head=newNode;
return;
}
Node tmp=head;
//逐个结点判断是否为空
while(tmp.next!=null){
tmp=tmp.next;
}
//若为空则把newNode赋给这个结点
tmp.next=newNode;
}

//删除某个结点
public Boolean deleteNode(int index){
if(index<1||index >length()){
//判断index是否为0或者大于链表的长度
return false;
}
//删除第一个元素
if(index==1){
head=head.next;
return true;
}
//若index>1;
int i=1;
Node preNode=head;
Node curNode=preNode.next;
while(curNode!=null){
if(i==index){
preNode.next=curNode.next;
return true;
}
preNode=curNode;
curNode=curNode.next;
i++;
}
return true;
}
//返回链表的长度
public int length() {
       int length=0;
       Node tmp=head;
       if(tmp!=null){
        length++;
        tmp=tmp.next;
       }
return length;
} //对链表进行排序
public Node orderNode(){
Node nextNode=null;
int tmp=0;
Node curNode=head;
while(curNode.next!=null){
nextNode=curNode.next;
while(nextNode!=null){
if(curNode.data>nextNode.data){
tmp=curNode.data;
curNode.data=nextNode.data;
nextNode.data=tmp;
}
nextNode=nextNode.next;
}
curNode=curNode.next;
}
return head;
}

//打印链表
public void printNode(){
Node curNode=head;
while(curNode!=null){
System.out.println(curNode.data);
curNode=curNode.next;
}
}

//链表去重
public void deleteDuplecate(Node head){
Hashtable <Integer,Integer> table=new Hashtable <Integer,Integer>();
Node tmp=head;
Node pre=null;
while(tmp!=null){
if(table.containsKey(tmp.data)){
pre.next=tmp.next;
}else{
table.put(tmp.data, 1);
pre=tmp;
}
tmp=tmp.next;
}
}
public static void main(String[] args) {
 MyLinkList mll=new MyLinkList ();
 System.out.println("链表长度为:"+mll.length());
 mll.addNode(3);
 mll.addNode(5);
 mll.addNode(8);
 mll.addNode(4);
 mll.addNode(4);
 mll.orderNode();
 mll.printNode();
 System.out.println("链表长度为:"+mll.length());
 System.out.println("-----------------------------------");
 System.out.println(mll.deleteNode(1));
 mll.deleteDuplecate(mll.head);
 mll.addNode(9);
 mll.printNode(); }
}
class Node{
Node next=null;
int data;
public Node(int data) {
this.data=data;
}
}