参考了 网上 部分 代码 单链表

来源:互联网 发布:无锡服务器数据恢复 编辑:程序博客网 时间:2024/04/30 06:00

单链表的基本操作 比较简单 但因为 自己在大二时候数据结构没学好 现在 重新 学一下希望 各位 能够 指正一下

/** * Link.java * Created on2017年4月17日 下午1:31:30 * All rights reserved */package javaPro;/** * @author 12091 * */public class Link {/** * @param args */public static void main(String[] args) {LinklinkList=new Link();linkList.addFirstNode(20);linkList.addFirstNode(19);linkList.addFirstNode(18);linkList.displayAllNodes();linkList.deleteBycontent(20);linkList.deleteByPos(0);linkList.displayAllNodes();System.out.println(linkList.findByIndex(0).data+"这是调用 findByIndex");System.out.println(linkList.findByData(19).data+"这是调用 findByData");linkList.insertByIndex(100, 1);linkList.displayAllNodes();linkList.deletefirst();linkList.displayAllNodes();}private Node first;private int pos;public Link(){this.first=null;}//增加一个first 节点public void addFirstNode(int data){Node node =new Node(data);node.next=first;first=node;}//按照索引删除一个节点public Node deleteByPos(int index){Node previous=first;Node current=first;while(pos!=index){previous=current;current=current.next;pos++;}if(first==current){first=first.next;}else{pos=0;previous.next=current.next;}return current;}//按照 data 删除一个节点public Node deleteBycontent(int data){Node previous=first;Node current=first;while(current.data!=data){if(current.next==null){return null;}previous=current;current=current.next;}if(current==first){first=first.next;}else{previous.next=current.next;}return current;}//打印 全部节点 数据部分(包括俩部分 数据 和指针(引用))public void displayAllNodes(){Node current=first;while(current!=null){System.out.println(current.data);current=current.next;}}//插入 节点public void insertByIndex(int data,int index){Node node=new Node(data);Node previous=first;Node current=first;while(pos!=index){previous=current;current=current.next;pos++;}if(current==first){node.next=first;System.out.println("ssssssss");first=node;}else{previous.next=node;node.next=current;pos=0;}}//删除 头结点并返回public Node deletefirst(){Node current=first;first=current.next;return current;}//根据 数据 查找 节点并返回 节点public Node findByData(int data){Node current=first;while(current.data!=data){if(current.next==null){return null;}current=current.next;}return current;}//根据 index查找 节点 并返回节点public Node findByIndex(int index){Node current=first;while(pos!=index){if(current.next==null){return null;}current=current.next;pos++;}pos=0;return current;}} 
代码运行无误 若有疑问的朋友 直接 评论 我会看的
0 0
原创粉丝点击