1.单链表的基础结构节点`
private class Node{
Node next;
int x;
Node(int p) {
this.x= p;
}
public Node() {
}
}
2.建立单链表
public Node head = new Node();
public int size;
public void add(int t) {
//建立单链表
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = new Node(t);
size++;
}
3.单链表的遍历
public void printData() {
//把第一个节点给临时节点temp,让temp遍历
Node temp = head;
while (temp != null) {
temp = temp.next;
System.out.print(temp.p.latitude+" ");
if(temp.next==null)//防止空指针
break;
}
System.out.println();
}
4.根据某个节点查询内容
public int get(int i) {
//查询链表的第i个节点的内容
if (i < 0 || i > size - 1) {
throw new ArrayIndexOutOfBoundsException("获取的位置不合法");
} else {
//把第一个节点给临时节点temp,让temp遍历
Node temp = head;
//counter用来计数,找到i在链表里的节点位置,头结点不算链表的真实节点,所以从-1开始计数
int counter = -1;
while (temp != null) {
if (counter == i) {
return temp.x;
}
temp = temp.next;
counter++;
}
}
return 0;
}
完整代码
class MyNode
{
//头结点,头结点是为了方便在下面的方法中遍历链表用的
public Node head = new Node();
public int size;
public void add(int t) {
//建立单链表
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = new Node(t);
size++;
}
public void printData() {
//遍历单链表,打印出单链表的数据
//把第一个节点给临时节点temp,让temp遍历
Node temp = head;
while (temp != null) {
temp = temp.next;
System.out.print(temp.x+" ");
if(temp.next==null)//防止空指针
break;
}
System.out.println();
}
public int get(int i) {
//查询链表的第i个节点的内容
if (i < 0 || i > size - 1) {
throw new ArrayIndexOutOfBoundsException("获取的位置不合法");
} else {
//把第一个节点给临时节点temp,让temp遍历
Node temp = head;
//counter用来计数,找到i在链表里的节点位置,头结点不算链表的真实节点,所以从-1开始计数
int counter = -1;
while (temp != null) {
if (counter == i) {
return temp.x;
}
temp = temp.next;
counter++;
}
}
return 0;
}
private class Node{
Node next;
int x;
Node(int p) {
this.x= p;
}
public Node() {
// TODO Auto-generated constructor stub
}
}
}
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int []num= {0,1,2,3,4,5,6};
MyNode m=new MyNode();
for(int i=0;i<num.length;i++)
{
m.add(num[i]);
}
//测试单链表中的数据
System.out.print("单链表中的数据为:");
m.printData();
//测试某个节点的内容
System.out.println("节点三号的内容为:"+m.get(3));
}
}
测试结果