java实现单链表
public class LinkListDemo1 {
private Node head=null;
private Node current;
public LinkListDemo1() {
// TODO Auto-generated constructor stub
}
//在链表尾部加入节点
public void addNode(int key) {
Node node=new Node(key);
if (head==null) {
head=node;
current=head;
}else {
current.next=node;
current=current.next;
}
}
//在指定位置加入节点
public void addNodePoint(int key,int b) {
Node node=head;
int c=1; //头结点是第一个结点
while (c!=b-1) {
node=node.next;
System.out.println(node.data+" a ");
c++;
}
System.out.println("节点位置为"+c);
//此时节点在第b前一个节点
Node bNode=new Node(key);
bNode.next=node.next;
node.next=bNode;
}
//删除指定结点的值
public void deleteNode(int a) {
if (head==null) {
System.out.println("为空链表");
}else {
Node node=head;
while (node.next.data!=a) {
node=node.next;
}
//此时node的节点值等于a前一个节点的值,下面进行删除a
node.next=node.next.next;
}
}
//删除指定位置的值
public void deleteNodePoint(int b) {
if (head==null) {
System.out.println("链表为空");
} else {
Node node=head;
int c=1; //头结点是第一个结点
while (c!=b-1) {
node=node.next;
c++;
}
System.out.println("节点位置为"+c);
//此时node节点在b前一个节点
node.next=node.next.next;
}
}
//查询节点的值
public void query(int b) {
Node node=head;
int c=1; //头结点是第一个结点
while (c!=b) {
node=node.next;
c++;
}
System.out.println("节点位置为"+c+"值为"+node.data);
}
//打印链表
public void print() {
if (head==null) {
System.out.println("结点为空");
}else {
Node cNode=head;
while (cNode!=null) {
System.out.print(cNode.data+" ");
cNode=cNode.next;
System.out.println(cNode==null);
}
}
}
class Node
{
int data;
Node next;
public Node(int data) {
// TODO Auto-generated constructor stub
this.data=data;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkListDemo1 list=new LinkListDemo1();
for (int i = 0; i <7; i++) {
list.addNode(i); //增加尾节点
}
list.addNodePoint(8, 4); //指定位置增加节点
list.deleteNode(4); //删除指定值节点
list.print(); //打印链表
list.query(4); //查询指定位置节点
list.deleteNodePoint(6); //删除指定位置节点
list.print(); //打印链表
}
}