直接上代码:
import java.util.Scanner;
public class LinkedList {
class Node {
int val;
Node next = null;
public Node(int val, Node next) {
this.val = val;
this.next = next;
}
public Node(int val) {
this(val, null);
}
}
private Node headNode; //头指针
private int size; //元素总数
public LinkedList() {
this.headNode = null;
this.size = 0;
}
//获取链表个数
public int getSize() {
return this.size;
}
//向链表头部添加元素
public void addNodeOnFirst(int data) {
Node newNode = new Node(data);
newNode.next = this.headNode;
this.headNode = newNode;
this.size++;
}
//向链表尾部添加元素
public void addNodeOnLast(int data) {
this.add(data, this.size);
}
//向指定位置添加元素
public void add(int data, int index) {
if (index < 0 || index > this.size) {
// System.out.println("下标越界异常");
throw new IllegalArgumentException("index is out error");
}
if (index == 0) {
this.addNodeOnFirst(data);
return;
}
Node preNode = this.headNode;
for (int i = 0; i < index - 1; i++) {
preNode = preNode.next;
}
Node newNode = new Node(data);
newNode.next = preNode.next;
preNode.next = newNode;
this.size++;
}
//删除链表指定位置的元素
public void remove(int index) {
if (index <= 0 || index > this.size) {
System.out.println("这个位置没任何元素");
return;
}
if (index == 1) {
headNode = headNode.next;
this.size--;
return;
}
Node temp = headNode;
for (int i = 1; i < index - 1; i++) {
temp = temp.next;
}
temp.next = temp.next.next;
this.size--;
}
//删除最后一个元素
public void removeLast() {
this.remove(this.size);
}
//删除链表第一个元素
public void removeFirst() {
this.remove(1);
}
//修改指定位置的元素值
public void update(int index, int data) {
if (index <= 0 || index > this.size) {
System.out.println("这个位置没任何元素");
return;
}
Node temp = headNode;
for (int i = 1; i < index - 1; i++) {
temp = temp.next;
}
temp.next.val = data;
}
//重写toString方法
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Node cur = this.headNode;
while (cur != null) {
sb.append(cur.val + "->");
cur = cur.next;
}
sb.append("NULL");
return sb.toString();
}
public static void main(String[] args) {
LinkedList linked = new LinkedList();
while (true) {
System.out.println(linked);
System.out.println("请选择菜单:");
System.out.println("1:添加 2:删除最后一个 3:删除指定位置 4:修改指定位置的值");
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
int in = Integer.parseInt(str);
if ("00".equals(str)) {
System.out.println("退出!");
break;
}
switch (in) {
case 1: {
System.out.print("请输入添加的元素:");
String s1 = scanner.nextLine();
linked.addNodeOnLast(Integer.parseInt(s1));
System.out.println("添加成功");
break;
}
case 2: {
System.out.println("已删除");
break;
}
case 3: {
System.out.print("删除第几个元素:");
String s1 = scanner.nextLine();
linked.remove(Integer.parseInt(s1));
System.out.println("删除成功");
break;
}
case 4: {
System.out.print("要第几个元素:");
String s1 = scanner.nextLine();
System.out.print("新的值为:");
String s2 = scanner.nextLine();
linked.update(Integer.parseInt(s1),Integer.parseInt(s2));
System.out.println("修改");
}
default: {
System.out.println("输入的不对哦!");
break;
}
}
}
}
}
测试结果: