package 二叉查找树;
public class linkedlist {
class Node{
Node next=null;
int data;
public Node(int data){
this.data=data;
}
}
public class mylinklist{
Node head=null;
public void addnode(int i) {
Node newNode=new Node(i);
if (head==null){
head=newNode;
return;
}
Node tmp=head;
while(tmp.next!=null)
{
tmp=tmp.next;
}
tmp.next=newNode;
}
public Boolean deleteNode(int index){
if(index<0||index>length()){
return false;
}
if(index==1){
head=head.next;
return true;
}
int i=2;
Node tmp=head;
while(i!=index){
tmp=tmp.next;
i++;
}
tmp.next=(tmp.next).next;
return true;
}
public int length(){
int length=0;
Node tmp=head;
while(tmp!=null){
length++;
tmp=tmp.next;
}
return length;
}
public Node orderlist(){
Node nextNode=null;
Node curNode=head;
int tmp=0;
while(curNode.next!=null){
nextNode=curNode.next;
while(nextNode!=null){
tmp=curNode.data;
if(curNode.data>nextNode.data){
curNode.data=nextNode.data;
nextNode.data=tmp;
}
nextNode=nextNode.next;
}
curNode=curNode.next;
}
return head;
}
public void printlist(){
Node tmp=head;
while(tmp!=null){
System.out.println(tmp.data);
tmp=tmp.next;
}
}
}
public static void main(String[] args){
linkedlist test1=new linkedlist();
mylinklist test=test1.new mylinklist();
test.addnode(5);
test.addnode(4);
test.addnode(3);
test.addnode(2);
test.addnode(1);
System.out.println(test.orderlist().data);
System.out.println("listLen:"+test.length());
test.deleteNode(3);
System.out.println(test.length());
test.printlist();
}
}
Java实现链表的增删排序
最新推荐文章于 2021-03-28 12:15:51 发布