Java实现单向链表

Java实现单向链表,源程序如下:

/*
* 结点类
*/
public class Node {
private int data;
private Node next;

public Node(int data) {
 this.data = data;
 this.next = null;
}
// 设置结点 数据的方法
public void setData(int data) {
 this.data = data;
}
// 设置结点指针的方法
public void setNext(Node next) {
 this.next = next;
}
// 获取结点数据的方法
public int getData() {
 return this.data;
}
// 获取下一个结点的方法
public Node getNext() {
 return this.next;
}
}

/*
* 单向链表类
*/
public class List{
private Node head;
public List() {
 this.head = null;
}
// 链表尾部添加结点
public void addNode(Node node) {
 if (head == null) {
  head = node;
}
 else {
  Node tmp = head;
  while(tmp.getNext() != null) {
   tmp = tmp.getNext();
  }
  tmp.setNext(node);
}
}
// 删除结点
public void deleteNode(Node node) {
 if (!isExist(node)) {
  System.out.println("结点不存在!");
  return ;
}
 if (this.head.getData() == node.getData()) {
  this.head = this.head.getNext();
  return ;
}
 Node tmp = this.head;
 while (tmp != null) {
  if (tmp.getNext().getData() == node.getData())
   break;
  tmp = tmp.getNext();
}
 tmp.setNext(tmp.getNext().getNext());
}
// 遍历链表
public void traverse() {
 if (this.head == null) {
  System.out.println("链表为空");
  return ;
}
 System.out.print("链表各结点为:");
 Node tmp = head;
 while (tmp != null) {
  System.out.print(tmp.getData() + " ");
  tmp = tmp.getNext();
}
 System.out.println();
}
// 判断结点是否存在
boolean isExist(Node node) {
 Node tmp = head;
 while (tmp != null) {
  if (tmp.getData() == node.getData())
   return true;
  tmp = tmp.getNext();
}
 return false;
}
}

public class TestList {
public static void main(String[] args) {
 // TODO Auto-generated method stub
// 实例化链表类,添加10个结点
 List list = new List();
 for (int i=0; i<10; i++) {
  list.addNode(new Node(i+1));
}
// 遍历链表
 list.traverse();
// 删除其中一个结点
 list.deleteNode(new Node(5));
// 删除后再次遍历链表
 list.traverse();
}
}

结束了~~

原文地址:https://www.cnblogs.com/godfriend/p/10752652.html