声明类:
public class LinkList {
LinkList next;
int val;
public LinkList(int val) {
this.val = val;
}
public LinkList getNext() {
return next;
}
public void setNext(LinkList next) {
this.next = next;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
}
头插法:
public static void insert1(int val) {
LinkList node = new LinkList(val);
//判断是否为空
if (head == null) {
head = node;
return;
}
node.next = head;
head = node;
}
尾插法:
public static void insert2(int val) {
LinkList node = new LinkList(val);
//判断是否为空
if (head == null) {
head = node;
return;
}
LinkList temp = head;
//遍历到最后插入
while (temp.next != null) {
temp = temp.next;
}
temp.next = node;
}
测试:
public static void main(String[] args) {
insert1(3);
insert2(4);
insert1(2);
insert2(5);
insert1(1);
insert2(6);
bianli();
}
//遍历
public static void bianli() {
LinkList temp = head;
while (temp != null) {
System.out.println(temp.val + " ");
temp = temp.next;
}
}
输出结果:
|