Java关于链表的增加、删除、获取长度、打印数值的实现
package com.shb.java; public class Demo8 { public Node headNode = null; /** * @param args * @date 2016-9-28 * @author shaobn */ public static void main(String[] args) { // TODO Auto-generated method stub Demo8 linkedList = new Demo8(); linkedList.addNode(1); linkedList.addNode(2); linkedList.addNode(34); linkedList.addNode(14); // System.out.println(linkedList.getLength()); linkedList.deleteNode(1); linkedList.printNode(); } /** * 插入到链表中 * @param data * @date 2016-9-28 * @author shaobn */ public void addNode(int data){ Node node = new Node(data); if(headNode==null){ headNode = node; return; } Node tmpNode = headNode; if(tmpNode.next==null){ tmpNode.next = node; return; } while(tmpNode.next!=null){ tmpNode = tmpNode.next; } tmpNode.next = node; } /** * 打印节点的值 * * @date 2016-9-28 * @author shaobn */ public void printNode(){ Node tmpNode = headNode; while(tmpNode!=null){ System.out.println(tmpNode.data); tmpNode = tmpNode.next; } } /** * 删除节点 * * @date 2016-9-28 * @author shaobn */ public void deleteNode(int index){ if(index<=0||index>this.getLength()){ throw new RuntimeException("索引选取不合适"); } int count = 1; Node tmpNode = headNode; while(tmpNode.next!=null){ count++; if(index==1){ headNode = tmpNode.next; break; } if(count==index){ tmpNode.next = tmpNode.next.next; } tmpNode = tmpNode.next; continue; } } /** * 获得本链表的长度 * @return * @date 2016-9-28 * @author shaobn */ public int getLength(){ int length = 0; Node tmpNode = this.headNode; while(tmpNode!=null){ length++; tmpNode = tmpNode.next; } return length; } } /** * 节点的类 * @author shaobn * @date 2016-9-28 * @package_name com.shb.java */ class Node{ public int data; public Node next; public Node(int data){ this.data = data; } }
吾宁做一叶扁舟,始航于湖边,遨游于海上,浪迹于江中。