**package data_structure;
/**
* @author DSL
* @date 2021/11/3
*/
public class test{
class Listnode {
int val;//数据域
Listnode next;//指针域
public Listnode() {
}
public Listnode(int val) {
this.val = val;
}
}
static Listnode headNode; //头指针
public void CreatList(Listnode node,int n){ //头插法,插入到表头
for (int i=0;i<n;++i){
Listnode newNode = new Listnode(i);//新节点
newNode.next=node.next;
node.next=newNode;
}
}
public void CreatList2(Listnode node,int n){
for (int i = 0; i < n; i++) {
Listnode newNode=new Listnode(i+1);
node.next=newNode;
node=newNode;
}
node.next=null;
}
public static void main(String[] args) {
test test=new test();
headNode=test.new Listnode();//头指针
new test().CreatList2(headNode,10);
System.out.println(headNode.val+"\n");
while(headNode.next!=null){
headNode=headNode.next;
System.out.print(headNode.val+" ");
}
}
}
- 尾插法是将表尾终端结点的指针指向新节点,然后将新节点定义为表尾终端节点。头节点相当于一个指针,不断地指向下一个新节点。
- 而头插法的头节点是没有动的。头插法是相当于链表的插入,就是插到头节点和第一个节点之间。
尾插法运行截图
头插法运行截图