Java版数据结构和算法学习笔记之线性结构链表篇
1. 单链表
单链表还是比较简单的,直接上程序吧~
1.1 单链表常用功能实现代码
package main;
public class Node {
public int data;
public Node node;
public Node next;
//为结点赋值
public void setData(int data) {
this.data=data;
}
//获取结点值
public int getData() {
return data;
}
//获取下一结点
public Node getNext() {
return this.next;
}
//增加结点
public void setNext(Node node) {
Node currentNode=this;
while(true) {
if(currentNode.next==null) {
break;
}
currentNode=currentNode.next;
}
currentNode.next=node;
}
//判断结点是否为最后一个
public boolean isLast() {
return next==null;
}
//删除下一结点
public void removeNext() {
//获取要删除的结点
Node nextNode=this.next;
if(nextNode.next==null) {
this.next=null;
}else {
this.next=nextNode.next;
}
}
//显示某结点后的所有结点信息
public void show() {
Node currentNode=this;
while(true) {
System.out.println(currentNode.getData()+" ");
if(currentNode.getNext()==null) {
break;
}
currentNode=currentNode.next;
}
}
//在某一结点后插入一个结点
public void insert(Node node) {
Node currentNode=this;
if(this.next==null) {
this.next=node;
}else {
Node nextNode=this.next;
this.next=node;
node.setNext(nextNode);
}
}
}
1.2 测试代码
package test;
import main.Node;
public class NodeTest {
public static void main(String[] args) {
Node n1=new Node();
Node n2=new Node();
Node n3=new Node();
Node n4=new Node();
n1.setData(1);
n2.setData(2);
n3.setData(3);
n4.setData(4);
//获取结点值并输出
//System.out.println(n1.getData());
//设置n2 为下一结点
n1.setNext(n2);
//输出下一结点值
//System.out.println(n1.getNext().getData());
//设置n3为下一结点
n1.setNext(n3);
//System.out.println(n1.getNext().getNext().getData());
//判断n3是否最后一个结点
//System.out.println(n3.isLast());
//删除下一结点
//n2.removeNext();
//查看是否删除成功
//System.out.println(n1.getNext().getData());
//n1.show();
//向n2后插入一个结点n4
n1.insert(n4);
n1.show();
}
}
2. 循环链表
与单链表类似。
package main;
public class LoopNode {
public int data;
public LoopNode node;
public LoopNode next=this;
//为结点赋值
public void setData(int data) {
this.data=data;
}
//获取结点值
public int getData() {
return data;
}
//获取下一结点
public LoopNode getNext() {
return this.next;
}
//增加结点
public void setNext(LoopNode node) {
LoopNode NextnextNode=this.next;
this.next=node;
node.next=NextnextNode;
}
//删除下一结点
public void removeNext() {
//获取要删除的结点
LoopNode nextNode=this.next;
if(nextNode.next==null) {
this.next=null;
}else {
this.next=nextNode.next;
}
}
}
package test;
import main.LoopNode;
public class LoopNodeTest {
public static void main(String[] args) {
LoopNode n1=new LoopNode();
LoopNode n2=new LoopNode();
LoopNode n3=new LoopNode();
LoopNode n4=new LoopNode();
n1.setData(1);
n2.setData(2);
n3.setData(3);
n4.setData(4);
n1.setNext(n2);
n2.setNext(n3);
n3.setNext(n4);
System.out.println(n4.getNext().getData());
System.out.println(n1.getNext().getData());
System.out.println(n2.getNext().getData());
System.out.println(n3.getNext().getData());
}
}