链表的创建
public class Node {
//数据域
public int data;
//下一个链接表位置
public Node next;
public Node() {
this.data = -1;
this.next = null;
}
}
链表的初始化
public void initial(Node head) {
head.next = null;
}
将头节点的后继指针域设为空,即除头结点之外没有任何节点.
可以理解为重新实例化了一个新的链表
头插法创建链表
//头插法插入数据
public void total(int x, Node head) {
//创建新节点作为插入节点
Node nov = new Node();
//为新节点封装数据
nov.data = x;
//将新节点放入链表中
nov.next = head.next;
head.next = nov;
}
创建一个新的节点作为插入节点方便操作
利用Node中的data为新节点赋值
插入时,先将新节点的下一个指向上一节点的下一个节点,防止原节点的下一节点丢失
尾插法创建链表
//尾插法创建链表
public void tail(Node head, int x) {
//创建新节点作为插入节点
Node inp = new Node();
//给新节点赋值
inp.data = x;
//寻找插入节点的位置
while(head.next != null){
head = head.next;
}
//插入节点
inp.next = head.next;
head.next = inp;
}
运用尾插法时,要先选找链表的队尾进行插入操作,插入时也应该注意指针丢失的问题.
在链表中插入数据
public void insert(Node head,int x,int d){
//创建插入的新节点
Node inp = new Node();
//为新节点赋值
inp.data = x;
//寻找新节点的插入位置
while(head.data != d){
head = head.next;
}
//插入节点
inp.next = head.next;
head.next = inp;
}
利用链表的数据域查找需要插入的位置,然后进行插入操作,插入时应注意指针丢失的问题
链表的打印
public void print(Node head) {
//创建一个临时节点,用来方便打印链表
Node p = head.next;
//判断p的下一节点是否为空,为空就跳出循环
while (p != null) {
//打印当前位置的数据
System.out.print(p.data + " ");
//寻找下一节点
p = p.next;
}
System.out.println(" ");
}
完整代码
建表类
public class Node {
//数据域
public int data;
//下一个链接表位置
public Node next;
public Node() {
this.data = -1;
this.next = null;
}
}
算法类
public class Method {
//初始化链表
public void initial(Node head) {
head.next = null;
}
//头插法插入数据
public void total(int x, Node head) {
//创建新节点作为插入节点
Node nov = new Node();
//为新节点封装数据
nov.data = x;
//将新节点放入链表中
nov.next = head.next;
head.next = nov;
}
//打印链表
public void print(Node head) {
//创建一个临时节点,用来方便打印链表
Node p = head.next;
//判断p的下一节点是否为空,为空就跳出循环
while (p != null) {
//打印当前位置的数据
System.out.print(p.data + " ");
//寻找下一节点
p = p.next;
}
System.out.println(" ");
}
//尾插法创建链表
public void tail(Node head, int x) {
//创建新节点作为插入节点
Node inp = new Node();
//给新节点赋值
inp.data = x;
//寻找插入节点的位置
while(head.next != null){
head = head.next;
}
//插入节点
inp.next = head.next;
head.next = inp;
}
//链表的插入
public void insert(Node head,int x,int d){
//创建插入的新节点
Node inp = new Node();
//为新节点赋值
inp.data = x;
//寻找新节点的插入位置
while(head.data != d){
head = head.next;
}
//插入节点
inp.next = head.next;
head.next = inp;
}
}