链表的java实现以及基本的增加,删除,排序操作
2015-06-28 22:41
851 查看
首先是存储节点信息的数据类
package com.list; public class Node { Node next=null; int data; public Node(int data){ this.data=data; } }链表的基本操作
package com.list; 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; } //删除第index个结点 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; } //返回结点的长度 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 tmp=head; while(tmp!=null){ System.out.println(tmp.data); tmp=tmp.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("listLen="+list.length()); System.out.println("before order:"); list.printList(); list.orderList(); System.out.println("after order:"); list.printList(); } }
相关文章推荐
- Java finally语句到底是在return之前还是之后执行?
- 新版Eclipse找不到Java EE Module Dependencies选项
- 新版Eclipse找不到Java EE Module Dependencies选项
- springMVC+velocity配置
- 新版Eclipse找不到Java EE Module Dependencies选项
- velocity模板在spring中的简单配置
- 进程互斥(三)Peterson算法
- 【工程管理】使用Ant构建struts2 web工程,自动编译,打包成war
- java基础复习
- springmvc+velocity+ Rest Services(xml,json)实例
- Java记录 -1- 基础JDK
- Eclipse BPEL插件下载地址
- Java基础之集合4
- Java反射-再次认识
- Java基础---反射
- Hibernate事务的属性
- ubuntu14.04安装pycharm
- 使用commons-daemon启动、关闭java程序
- Java之旅:简单一句话---J2EE13个规范
- 《Java从入门到精通》第十一章学习笔记