java 連結串列的常見操作
阿新 • • 發佈:2018-12-05
1.定義連結串列的節點類
class Node {
protected Node next; // 下一節點
protected String data;// 資料
public Node(String data) {
this.data = data;
}
// 顯示此節點
public void show() {
System.out.print(data+"、");
}
}
class LinkList { public Node first; // 定義頭結點 private int pos = 0;// 節點的位置 public LinkList() { this.first = null; } // 插入一個頭節點 public void addFirstNode(String data) { Node node = new Node(data); node.next = first; first = node; } // 刪除一個頭結點,並返回頭結點 public Node deleteFirstNode() { Node tempNode = first; first = tempNode.next; return tempNode; } // 在任意位置插入節點 在index的後面插入 public void add(int index, String data) { Node node = new Node(data); Node current = first; Node previous = first; while (pos != index) { previous = current; current = current.next; pos++; } node.next = current; previous.next = node; pos = 0; } // 刪除任意位置的節點 public Node deleteByPos(int index) { Node current = first; Node previous = first; while (pos != index) { pos++; previous = current; current = current.next; } if (current == first) { first = first.next; } else { pos = 0; previous.next = current.next; } return current; } // 根據節點的data刪除節點(僅僅刪除第一個) public Node deleteByData(String data) { Node current = first; Node previous = first; // 記住上一個節點 while (current.data != data) { if (current.next == null) { return null; } previous = current; current = current.next; } if (current == first) { first = first.next; } else { previous.next = current.next; } return current; } // 顯示出所有的節點資訊 public void displayAllNodes() { Node current = first; while (current != null) { current.show(); current = current.next; } System.out.println(); } // 根據位置查詢節點資訊 public Node findByPos(int index) { Node current = first; if (pos != index) { current = current.next; pos++; } return current; } // 根據資料查詢節點資訊 public Node findByData(String data) { Node current = first; while (current.data != data) { if (current.next == null) return null; current = current.next; } return current; } }
3.測試連結串列操作:
public class Client { public static void main(String[] args) { LinkList linkList = new LinkList(); linkList.addFirstNode("A"); linkList.addFirstNode("B"); linkList.addFirstNode("C"); linkList.add(1, "D"); linkList.add(2, "E"); linkList.add(3, "F"); linkList.displayAllNodes(); Node node = linkList.deleteByData("A"); System.out.println("node : " + node.data); linkList.displayAllNodes(); Node node1 = linkList.findByPos(0); System.out.println("node1: " + node1.data); Node node2 = linkList.findByData("E"); System.out.println("node2: " + node2.data); } }
4.執行結果:
C、D、E、F、B、A、
node : A
C、D、E、F、B、
node: C
node: E