码迷,mamicode.com
首页 > 编程语言 > 详细

Java实现单向链表

时间:2019-04-22 21:10:42      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:his   stl   ++   list()   oid   java实现   exist   []   eth   

/*
 * 结点类
 */
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();
 }
}

Java实现单向链表

标签:his   stl   ++   list()   oid   java实现   exist   []   eth   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!