链表
链式存储结构
内存不连续
以节点的方式存储
节点包含数据域和指针域
链表分带有节点和无头节点的链表
单链表
各种操作的依赖
无论插入删除修改遍历我们所需要的实际上只需要让一个新节点(temp【在c里就是指针,Java中没有指针的概念,但其实就是类节点】)获取到我们要进行操作的链表就行
主要
搞清怎么操作指针域就行
temp = head
temp = temp.next
代码
链表节点
package linklist;
public class ListNode {
public int id;
//数据域
public String data;
//指针域
public ListNode next;
public ListNode(int id,String data){
this.id = id;
this.data = data;
}
@Override
public String toString() {
return "ListNode{" +
"id=" + id +
", data='" + data + '\'' +
'}';
}
}
单链表实体类
package linklist;
public class SingleLinkList {
//先初始化一个头节点,头节点不存放具体数据
private ListNode head;
public void initSingLinkList() {
head = new ListNode(0, "");
}
//添加节点
public void insertNode(ListNode listNode) {
//使用temp指针进行遍历
ListNode temp = head;
while (true) {
if (temp.next == null) {
break;
}
temp = temp.next;
}
temp.next = listNode;
}
//打印链表
public void showSingleLinkList() {
if (isEmpty()) {
return;
}
ListNode temp = head.next;
while (true) {
if (temp == null) {
return;
}
System.out.println(temp);
temp = temp.next;
}
}
//判断链表是否为空
public boolean isEmpty() {
if (head.next == null) {
System.out.println("链表为空");
return true;
}
return false;
}
//按照id顺序添加节点
public void insertByOrder(ListNode listNode) {
ListNode temp = head;
boolean flag = false;
while (true) {
if (temp.next == null) {
break