关于头插法,可以next可以理解成前一个节点地址,插入顺序:
1、头节点传入,开始创建a数据,头节点的next指向a数据的内存地址,a节点的next替换成头节点的
2、头节点再传入,创建b数据,头节点的next又换成了指向b的内存地址,b节点的next替换头节点的a;
总结一下:插入时候,一直在头节点的上面插入数据,原来的数据被“顶”上去了;
头插法遍历的时候,头节点开始,一个一个往上遍历。这样最后插入的就作为第一个输出出来了;
尾插法编练插入,比较好理解,就是一直在“尾巴”追加,遍历时候从头开始,第一个插入的就第一个输出出来;
public class test {
static node headnode;
class node {
private node next;//指针
private int data;//数据域
}
//尾插法创建单链表 队列形式先进先出
public void back(node node, int data) {
if (data < 10) {
node next = new node();
next.data = data;
next.next = null;
node.next = next;
back(next, ++data);
}
}
//头插法创建单链表 栈形式先进后出
public void head(node node, int data) {
if (data < 10) {
node next = new node();
next.next = node.next;
next.data = data;
node.next = next;
system.out.println("递归参数:" + node.data);
head(node, ++data);
}
}
public static void main(string[] args) {
test test = new test();
headnode = test.new node();//头指针
// new test().back(headnode, 0);//前插法
new test().head(headnode, 0);//后插法
system.out.println("创建后的链表是:");//0 1 2 3 4 5 6 7 8 9 10
while (headnode.next != null) {
headnode = headnode.next;
system.out.print(headnode.data + " ");
}
}
}
//————————————————
//版权声明:本文为csdn博主「另一个绝影」的原创文章,遵循 cc 4.0 by-sa 版权协议,转载请附上原文出处链接及本声明。
//原文链接:https://blog.csdn.net/weixin_37817685/article/details/83305972
如对本文有疑问, 点击进行留言回复!!
SpringBoot引用阿里easyexcel,Excel导出返回浏览器下载
HashMap、Hashtable、ConcurrentHashMap三者间的异同
解决RecycleView 中Item包含Edittext时,滑动view复用导致数据错乱的问题
多线程、同步工作原理、死锁案例、Lock接口、线程的生命周期的讲解及实现
网友评论