您的位置:首页 > 编程语言 > Java开发

Java实现链表的插入,删除,排序,输出

2017-04-01 19:28 519 查看
//链表的数据结构:

package test;

 class Node {

     Node next=null;

     int data;

     public Node(int data){

    this.data=data;

     }
}

//链表操作 的实现:

package test;

import com.oj.Main1;

public class MyLinkedList {
Node head=null;
public void addNode(int d){
Node newNode=new Node(d);
if(head==null){
head=newNode;
return;
}
Node tmp=head;
while(tmp.next!=null){
tmp=tmp.next;
}
tmp.next=newNode;
}
/**

* @param index 删除第index个结点
* @return
*/
public Boolean deleteNode(int index){
 if(index<1||index>length()){
 return false;
 }
 if(index==1){
 head=head.next;
     return true;
 }
 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;
}
/**

* @return
*/

    public int length(){

    int length=0;

    Node tmp=head;

    while(tmp!=null){

    length++;

         tmp=tmp.next;

    }

    return length;

    }

    /**

     * 对链表排序

     * 返回排序后的头结点 

     */

    public Node orderList(){

    Node nextNode=null;

    int temp=0;

    Node curNode=head;

    while(curNode.next!=null){

    nextNode=curNode.next;

    while(nextNode!=null){

    if(curNode.data>nextNode.data){

    temp=curNode.data;

    curNode.data=nextNode.data;

    nextNode.data=temp;

    }

    nextNode=nextNode.next;

    }

    curNode=curNode.next;

    }

    return head;

    }

    public void printList(){

    Node temp=head;

    while(temp!=null){

    System.out.println(temp.data);

    temp=temp.next;

    }

    }

    public static void main(String[] args) {
MyLinkedList list=new MyLinkedList();
list.addNode(5);
list.addNode(3);
list.addNode(1);
list.addNode(3);
System.out.println("长度: "+list.length());
System.out.println("排序前:");
list.printList();
System.out.println("排序前:");
list.orderList();
System.out.println("排序后:");
list.printList();
System.out.println("删除结点后:");
list.deleteNode(3);
list.printList();
}

    

    

    

    

    

    

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐