今天到xxxx公司面试,前面的一些题目都是网上的一些面试题,最后一题考察的是数据结构,让介绍大学里学习的数据结构,并用代码实现链表的增加,删除,查询。这个之前在写练习时,写过链表的Demo,但是在这个关键时刻却忘了,不知道该怎么写,回来之后翻开之前写的代码重新看了一遍,在这里,我把我之前写的代码粘贴出来,供大家学习,希望大家能有所收获:
package link; public class Link { /** * 保存每一个节点,此处为了方便直接定义成内部类 * @author binchen * */ class Node{ private String data; private Node next; //保存下一个节点 public Node(){} public Node(String data){ this.data = data; //通过构造方法设置节点内容 } public String getData() { return data; } public void setData(String data) { this.data = data; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } /** * 输出节点内容 */ public void print(){ System.out.println(this.data + "\t"); if(this.next != null){ this.next.print(); } } /** * 添加节点内容 * @param newNode */ public void add(Node newNode){ //将节点加入到合适的位置 if(this.next == null){ this.next = newNode; }else{ //如果不为空,则需要向下继续找next this.next.add(newNode); } } /** * 查找节点 * @param data * @return */ public boolean search(String data){ //内部搜索的方法 if(this.data.equals(data)){ return true; }else{ //向下继续判断 if(this.next != null){ //如果不等于null,就继续向下查找下去 return this.next.search(data); } return false; } } /** * 删除节点 * @param data */ public void deleteNode(Node previous , String name){ if(name.equals(this.data)){ previous.next = this.next; }else{ if(this.next != null){ this.next.deleteNode(this, name); } } } }; private Node root; //链表中必然存在一个根节点 public void setRoot(Node root){ this.root = root; } public Node getRoot(){ return this.root; } /** * 添加节点内容 * @param data */ public void addNode(String data){ //增加节点 Node newNode = new Node(data); //定义新的节点 if(this.root == null){ //判断根节点是否存在,如果不存在就将第一个节点设置成根节点 this.root = newNode; //将第一个节点设置成根节点 }else{ //不过如果存在,【不是根节点】,放到最后一个节点之后 this.root.add(newNode); } } /** * 输出全部的节点内容 */ public void printNode(){ if(this.root != null){ //如果根元素不为空 this.root.print(); //调用节点类中的输出操作 } } /** * 查找节点 * @param name * @return */ public boolean contains(String name){ return this.root.search(name); //调用node类中的查找方法 } /** * 删除节点 * @param name */ public void deleteNode(String data){ if(this.contains(data)){ //判断节点是否存在 //一定要判断此元素现在是不是与根元素相等 if(this.root.data.equals(data)){ //内容是根节点 this.root = this.root.next; //修改根节点,将第一个节点设置成根节点 }else{ this.root.next.deleteNode(root,data); } } } }