欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

链表的增删改查(Java编程)

时间:2023-06-18

public class linked { private Node head; private Node last; private int size; public linked(){ size = 0; } public linked(Node head,Node last){ this.head = head; this.last = last; head.next = last; size = 2; } public void insert(Node node,int index)throws Exception{ if (index<0||index>size){ throw new Exception("链表越界"); } //如果还没有初始化 if (size == 0){ this.head = node; this.last = node; } //插在尾部 else if (index==size){ last.next = node; last = last.next; } //插在头部 else if (index == 0){ node.next = head; head = node; } //插在中间 else{ node.next = getNode(index-1).next; getNode(index-1).next = node; } size++; } public void delete(int index)throws Exception{ if (index<0||index>size){ throw new Exception("链表越界"); } if (index == 0){ head = head.next; } else if (index == size-1) { getNode(index - 1).next = null; last = getNode(index - 1); } else{ getNode(index-1).next = getNode(index).next; } size--; } public Node getNode(int index){ int i = 0; Node n1 = head; while(true){ if (i == index){ return n1; } n1 = n1.next; i++; } } public void update(int index,String date){ getNode(index).date = date; } public void output(){ Node n1 = head; for (int i = 0; i < size; i++) { System.out.println(n1+" "); n1 = n1.next; } } public static void main(String[] args)throws Exception { Node n1 = new Node("1号"); Node n2 = new Node("2号"); Node n3 = new Node("3号"); Node n4 = new Node("4号"); Node n5 = new Node("5号"); Node n6 = new Node("6号"); linked linked1 = new linked(n1, n5); linked1.insert(n2,1); linked1.insert(n3,2); linked1.insert(n4,3); linked1.insert(n6,0); linked1.update(0,"0号"); linked1.output(); linked1.delete(0); linked1.delete(2); linked1.delete(3); linked1.output(); }}class Node{ String date; Node next; public Node(){} public Node(String date,Node next){ this.date = date; this.next = next; } public Node(String date){ this.date = date; } @Override public String toString() { return date; }}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。