android面试时经常也会被问到数据结构和算法的问题,最近有时间,写点实例。
1. 节点定义 Node.java
package com.demo;
public class Node {
String name;
Node next;
public Node(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String toString() {
return name+"->";
}
}
2. 实例调用 LinkListDemo
package com.demo;
public class LinkListDemo {
private static Node head = null; //链表头地址
private static Node cursor = null; //链表游标
public static void main(String args[]){
LinkListDemo main = new LinkListDemo();
//添加节点
for(int i=1;i<10;i++){
Node node = new Node("node"+i);
main.addNode(node);
}
//遍历链表
Node temp = null;
for(temp = head;temp!=null;temp = temp.next){
System.out.print(temp.toString());
}
}
/**
* 初始化链表
* @param node
*/
public void initList(Node node){
head = node;
cursor = head;
head.next = null;
}
/**
* 添加一个节点
*/
public void addNode(Node node){
if(head == null){
initList(node);
}else{
Node temp = cursor;
temp.next = node;
cursor = node;
}
}
}
3.遍历结果演示:
node1->node2->node3->node4->node5->node6->node7->node8->node9->