- 链表是以节点的方式来存储, 是链式存储
- 每个节点包含 data 域, next 域:指向下一个节点.
- 如图:发现 链表的各个节点不一定是连续存储.
- 链表分 带头节点的链表和 没有头节点的链表,根据实际的需求来确定
单向链表增删改查代码块
class StudentNode
{
int no;
String name;
//存储下一个节点的信息
StudentNode next;
public StudentNode(int no, String name) {
this.no = no;
this.name = name;
}
@Override
public String toString() {
return "StudentNode{" +
"no=" + no +
", name='" + name +
'}';
}
}
class MyLinkedList {
private StudentNode head = new StudentNode(0, "");
public void add(StudentNode studentNode) {
StudentNode temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = studentNode;
}
//根据no的大小,向指定位置插入数据,如果已经有相同no的节点,则添加失败,否则添加成功
public void addByNo(StudentNode studentNode)
{
StudentNode temp = head;
boolean flag=false;
while(true)
{
//已经到了链表的末尾就break
if(temp.next==null)
{
break;
}
if(temp.next.no>studentNode.no&&temp.no<studentNode.no)
{
break;
}
else if(temp.no==studentNode.no)
{
flag=true;
break;
}
temp=temp.next;
}
if(flag)
{
System.out.println("准备插入的学生编号"+studentNode.no+"已经存在,不能插入");
}
else
{
studentNode.next=temp.next;
temp.next=studentNode;
}
}
//打印链表所有元素
public void all()
{
StudentNode temp=head;
while (temp!=null)
{
System.out.println(temp);
temp=temp.next;
}
}
//更新链表
public void update(StudentNode studentNode)
{
StudentNode temp=head;
if(temp.next==null)
{
System.out.println("链表为空,不能修改元素");
}
boolean flag=false;
while (true)
{
if(temp==null)
{
break;
}
else if(temp.no==studentNode.no)
{
flag=true;
temp.name=studentNode.name;
}
temp=temp.next;
}
if(!flag)
{
System.out.println("修改失败,不存在编号为"+studentNode.no+"的节点");
}
}
//删除链表
public void delete(int no)
{
StudentNode temp=head;
boolean flag=false;
while(true)
{
if(temp.next==null)
{
break;
}
if(temp.next.no==no)
{
flag=true;
temp.next=temp.next.next;
break;
}
temp=temp.next;
}
if(!flag)
{
System.out.println("要删除的编号为"+no+"的节点不存在");
}
}
}
public class Test {
public static void main(String[] args) {
StudentNode studentNode1=new StudentNode(1,"郎云松1号");
StudentNode studentNode2=new StudentNode(2,"郎云松2号");
StudentNode studentNode3=new StudentNode(3,"郎云松3号");
StudentNode studentNode4=new StudentNode(4,"郎云松4号");
StudentNode studentNode5=new StudentNode(1,"郎云松1号盗版");
StudentNode studentNode6=new StudentNode(6,"郎云松6号");
StudentNode studentNode7=new StudentNode(7,"郎云松7号");
StudentNode studentNode8=new StudentNode(5,"郎云松5号");
StudentNode studentNode9=new StudentNode(6,"郎云松6号修改");
MyLinkedList myLinkedList=new MyLinkedList();
myLinkedList.add(studentNode1);
myLinkedList.add(studentNode2);
myLinkedList.add(studentNode3);
myLinkedList.add(studentNode4);
myLinkedList.addByNo(studentNode8);
myLinkedList.addByNo(studentNode5);
myLinkedList.addByNo(studentNode6);
myLinkedList.addByNo(studentNode7);
myLinkedList.update(studentNode9);
myLinkedList.delete(7);
myLinkedList.delete(1);
myLinkedList.all();
}
}