当前位置: 代码迷 >> 综合 >> Java单链表实现
  详细解决方案

Java单链表实现

热度:16   发布时间:2023-10-08 19:58:53.0
package com.datastruct;public class ListNode {Node head;int length;// 单链表长度public int size() {return length;}// 头插法public void addNodeHead(Node node) {node.next = head;head = node;length++;}// 尾插法public void addNodeTail(Node node) {// 也可以使用长度来判断if (head == null) {head = node;} else {Node n = head;while (n.next != null) {n = n.next;}n.next = node;}length++;}// 在指定位置上插入节点public void addNode(int index, Node node) {if (index < 0 || index > length) {throw new IllegalArgumentException();}Node n = head;Node previous = head;int pos = 0;while (pos != index) {previous = n;n = n.next;pos++;}if (n == head) {node.next = head;head = node;} else {node.next = n;previous.next = node;}length++;}// 查找指定位置节点public Node findNodeByIndex(int index) {Node n = head;int pos = 0;while (pos != index) {n = n.next;pos++;}return n;}// 获得所有节点public void getAllNodes() {Node n = head;StringBuilder sb = new StringBuilder();while (n != null) {sb.append(n.data).append(" ");n = n.next;}System.out.println(sb.toString());}// 删除指定位置节点public void delNodeByIndex(int index) {if (index < 0 || index > length) {throw new IllegalArgumentException();}Node n = head;Node previous = head;int pos = 0;while (pos != index) {previous = n;n = n.next;pos++;}if (n == head) {head = head.next;} else {previous.next = n.next;}length--;}    // 清空单链表public void clear() {length = 0;head = null;}
}package com.datastruct;public class Node {int data;Node next;public Node(int data) {this.data = data;}@Overridepublic String toString() {return  "data=" + data ;}
}class TestLinked1 {public static void main(String[] args) {ListNode list = new ListNode();list.addNodeTail(new Node(1));list.addNodeTail(new Node(2));list.addNodeTail(new Node(3));list.addNodeTail(new Node(4));// 查找指定节点list.getAllNodes();Node node = list.findNodeByIndex(0);System.out.println(node.data);// 头插法//list.addNodeHead(new Node(7));// 指定位置插入节点list.getAllNodes();list.addNode(4,new Node(8));list.getAllNodes();list.delNodeByIndex(4);list.getAllNodes();list.clear();list.getAllNodes();}
}