链表是基本的数据结构
特点:可以用任意蚁族存储单元来存储单链表中的数据元素
数据元素值、直接后继元素的信息-----节点
Java实现单链表的增、删、排序、获取链表长度、打印链表
package com.yaxin.linkedlist; public class MyLinkedList { Node head=null; //链表头的引用 /** * 向链表中插入数据 * @param data */ public void addNode(int data) { Node newNode=new Node(data); if(null==head) { head=newNode; return; } Node tmp=head; while(tmp.next!=null) { tmp=tmp.next; } tmp.next=newNode; } /** * 删除链表中指定索引处的数据 * @param index * @return 成功返回true 说明删除成功 否则返回false */ public boolean deleteNode(int index) { if(index<0||index>=length()) { return false; } if(index==0) { head=head.next; return true; } int count=1; Node tmp=head.next; while(count!=index) { tmp=tmp.next; } tmp.next=tmp.next.next; return true; } /** * 获取链表的长度 * @return 返回链表的长度 */ public int length() { if(null==head) { return 0; } int count=1; Node tmp=head; while(null!=tmp.next) { count++; tmp=tmp.next; } return count; } /** * 对链表进行排序 * @return 返回排序后的头节点 */ public Node orderList() { if(length()<1) { return null; } int i; Node currentNode=head; Node nextNode=head.next; while(null!=currentNode) { while(null!=nextNode) { if(currentNode.data>nextNode.data) { i=currentNode.data; currentNode.data=nextNode.data; nextNode.data=i; } nextNode=nextNode.next; } currentNode=currentNode.next; } return head; } /** * 打印链表 */ public void printList() { Node tmp=head; while(null!=tmp) { 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(); } } class Node { Node next=null; int data; public Node(int data) { super(); this.data = data; } }
运行结果: