在Java中,线性表可以通过数组或链表来实现。这里我将向您展示如何使用这两种方法来实现线性表。
- 使用数组实现线性表:
public class LinearList { private int[] data; private int size; public LinearList(int capacity) { data = https://www.yisu.com/ask/new int[capacity];"hljs">int value) { if (size == data.length) { System.out.println("线性表已满,无法添加元素"); return; } data[size++] = value; } public int get(int index) { if (index < 0 || index >= size) { System.out.println("索引越界"); return -1; } return data[index]; } public int size() { return size; } public static void main(String[] args) { LinearList list = new LinearList(5); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); for (int i = 0; i < list.size(); i++) { System.out.println("索引 " + i + " 的元素: " + list.get(i)); } } }
- 使用链表实现线性表:
public class Node { int value; Node next; public Node(int value) { this.value = https://www.yisu.com/ask/value;"hljs">int value) { Node newNode = new Node(value); if (head == null) { head = newNode; } else { Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; } size++; } public int get(int index) { if (index < 0 || index >= size) { System.out.println("索引越界"); return -1; } Node current = head; for (int i = 0; i < index; i++) { current = current.next; } return current.value; } public int size() { return size; } public static void main(String[] args) { LinkedList list = new LinkedList(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); for (int i = 0; i < list.size(); i++) { System.out.println("索引 " + i + " 的元素: " + list.get(i)); } } }
以上代码分别使用数组和链表实现了线性表的基本操作,如添加元素、获取指定索引的元素和获取线性表的大小。您可以根据实际需求选择合适的数据结构来实现线性表。