单向链表特点实现

来源:互联网 发布:talkingdata数据造假 编辑:程序博客网 时间:2024/06/05 16:21

//结点

public class LinkNode {public int value;//值public String key;//关键字public LinkNode nextNode = null;public LinkNode(int value,String key){this.value = value;this.key = key;}public LinkNode(){}public void println(){System.out.println("结点值:" + value+"   结点key "+key);}}

//链表类

public class LinkList {LinkNode headNode = new LinkNode();//头结点,只保存列表中第一个结点的引用LinkNode tempLinkNode;//临时保存当前的操作的结点//判断是否是空链表,如果头结点没有next地址为空,则是空链表public boolean isEmpty(){return headNode.nextNode == null?true:false;}//添加结点(返回添加的结点)public LinkNode AddNode(int value){LinkNode linkNode = null;if (isEmpty()) {linkNode = new LinkNode(value, value+"");headNode.nextNode = linkNode;tempLinkNode = linkNode;}else{linkNode = new LinkNode(value, value+"");tempLinkNode.nextNode = linkNode;tempLinkNode = linkNode;}return tempLinkNode;}public LinkNode removeFirst(){LinkNode tempLinkNode = headNode.nextNode; headNode.nextNode = tempLinkNode.nextNode;return null;}//查找指定结点public LinkNode findLinkNode(String findkey){LinkNode  currentNode = headNode.nextNode;while(true){if (currentNode == null) {System.out.println("没有找到该结点");return null;}if (currentNode.key.equals(findkey)) {System.out.println("找到的结点:值为"+currentNode.value + " key为"+currentNode.key);return currentNode;}currentNode = currentNode.nextNode;}}//删除结点     public LinkNode delNode(String delkey){LinkNode privousNode = null;//当前结点的上一个结点LinkNode currentNode = null;//当前结点LinkNode firstNode = headNode.nextNode;//第一个结点currentNode = firstNode;privousNode = firstNode;while (currentNode != null && !currentNode.key.equals(delkey)) {        privousNode = currentNode;    currentNode = currentNode.nextNode;}if (currentNode == null) {    System.out.println("没有找到想要删除的数据");return null;}        privousNode.nextNode = currentNode.nextNode;//如果删除的是最后一个currentNode.nextNode == null;          return currentNode;}//列表末尾插入public LinkNode addLastNode(int value){ LinkNode linkNode = new LinkNode(value, value+"");linkNode.nextNode = null;tempLinkNode.nextNode = linkNode;tempLinkNode = linkNode;return linkNode;}public LinkNode addPositionNode(int position){return null;}//遍历结点public void lookLinkList(){LinkNode currentLinkNode = headNode.nextNode;while (currentLinkNode != null) {System.out.println("结点值:  "+ currentLinkNode.value);currentLinkNode = currentLinkNode.nextNode;}}}
//展示

public static void main(String[] args) {LinkList linkList = new LinkList();for (int i = 0; i < 10; i++) {linkList.AddNode(i);}//遍历,必须是从头部一直向下遍历 linkList.lookLinkList();//查找指定元素System.out.println("\n查找指定元素");linkList.findLinkNode("3");//删除指定元素再遍历System.out.println("\n遍历元素");linkList.delNode("9");linkList.lookLinkList();//删除第一个元素System.out.println("\n删除列表第一个元素");linkList.removeFirst();linkList.lookLinkList();//末尾添加元素System.out.println("\n末尾添加一个元素");for (int i = 10; i < 15; i++) {linkList.addLastNode(i);}linkList.lookLinkList();}



0 0
原创粉丝点击