public class Node {
private int data;
private Node next;
public Node(int data){
this.data=data;
}
public void SetData(int data){
this.data=data;
}
public int getData() {
return data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
package liu;
public class SingleListNode {
private Node root;
private Node current;
private int Pos;
private int length;
//初始化
public SingleListNode(){
current=null;
root=null;
Pos=0;
length=0;
}
//向链表尾部添加数据
public void Add(int n){
//当链表为空时
if(root==null){
Node temp=new Node(n);
temp.setNext(null);
root=temp;
current=temp;
length++;
}
//当原链表中有数据时
else{
Node temp=new Node(n);
temp.setNext(null);
current.setNext(temp);
current=temp;
length++;
}
}
//向链表中指定位置添加数据
public void Insert(int Position,int data){
if(Position<1){
System.out.println("overflow");
System.exit(0);
}
else{
Node temp=new Node(data){
if(Position==1){
temp.setNext(root);
root=temp;
}
else if(Position>length){
temp.setNext(null);
current.setNext(temp);
}else{
Node pre=root;
Node aft=root;
while(Pos!=Position){
pre=aft;
aft=aft.getNext();
Pos++;
}
pre.setNext(temp);
temp.setNext(aft);
}
length++;
}
Pos=1;
}
public int Getlength(){
return length;
}
//删除链表中数据
public void Dele(int Position){
Node pre=root;
Node aft=root;
if(Position<1 || Position>length){
System.out.println("overflow!");
System.exit(0);
}
else if(length==1){
root=current=null;
}
else{
while(Pos!=Position){
Pos++;
pre=aft;
aft=aft.getNext();
}
pre.setNext(aft.getNext());
}
Pos=1;
length--;
}
//对链表中数据进行排序
public void Sort(){
int temp;
for(int i=1;i<length;i++){
Node pre=root;
Node aft=root.getNext();
for(int j=i+1;j<=length;j++){
if(pre.getData()>aft.getData()){
temp=pre.getData();
pre.SetData(aft.getData());
aft.SetData(temp);
}
pre=pre.getNext();
aft=aft.getNext();
}
}
}
//对链表中数据进行反序
public void AntiSortDisplay(){
Node anti=null;
while(root!=null){
Node item=new Node(root.getData());
item.setNext(anti);
anti=item;
root=root.getNext();
}
Node temp=anti;
while(temp!=null){
System.out.print(temp.getData()+" ");
temp=temp.getNext();
}
}
public void Display(){
Node temp=root;
while(temp!=null){
System.out.print(temp.getData()+" ");
temp=temp.getNext();
}
}
//主函数测试
public static void main(String[] args) {
SingleListNode L=new SingleListNode();
L.Add(0);
L.Add(1);
L.Add(3);
L.Add(4);
L.Display();
L.Dele(1);
System.out.println();
L.Display();
L.Add(8);
L.Add(9);
L.Add(3);
L.Insert(1, 100);
System.out.println();
L.Display();
L.Sort();
System.out.println();
System.out.println(L.Getlength());
L.Display();
System.out.println();
L.AntiSortDisplay();
}
}