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();
}
}

結束了~~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM