java实现单链表的基本操作

来源:互联网 发布:概率图模型 知乎 编辑:程序博客网 时间:2024/05/17 23:15
package link;/** * 单链表模型:实现插入、删除、查找、反转、输出等操作 * @author USER * *///结点类class Node{protected int data; //结点数据protected Node next;//结点指针//结点构造方法public Node(int data) {this.data=data;}public void print() {System.out.print(data+" ");}}//链表类class Link{public  Node head;//头结点private int pos = 0;//结点位置public Link(){this.head = null;}//插入一个头结点public void addHeadNode(int data) {Node node = new Node(data);node.next = head;//此处head为nullhead = node;//此处head为新加入的结点}//在任意位置index处插入一个结点,插入结点在index之后的那个结点public void add(int index, int data) {Node node = new Node(data);Node previous = head;Node current = head;while (pos!=index) {previous = current;current = current.next;pos++;}node.next = current;previous.next = node;pos = 0;}//在任意位置index处删除一个结点,删除的是第index个结点,不能删除第一个结点public void delete(int index) {Node previous = head;Node current = head;pos++;while (pos!=index) {previous = current;current = current.next;pos++;}previous.next = current.next;pos = 0;}//删除头结点public void deleteHead() {Node temp = head;head = temp.next;}//根据结点位置查找结点信息,注意:index是指第几个位置,pos是从0开始代表第一个位置public Node findByPos(int index) {Node current = head;pos++;while (pos != index) {current = current.next;pos++;}pos = 0;return current;}//根据结点数据查找结点信息public Node findByData(int data) {Node current = head;while (current.data != data) {if (current.next == null) {return null;}else {current = current.next;}}return current;}//整个链表的长度public  int length() {int size = 0;Node current = head;while (current != null) {current = current.next;size++;}return size;}//显示整个链表public void show() {Node current = head;while (current != null) {current.print();current = current.next;}System.out.println();}}public class MySingleLinkList {public static void main(String[] args) {Link list = new Link();list.addHeadNode(10);list.show();//10list.add(1, 12);list.add(2, 13);list.add(3, 14);list.add(4, 15);list.add(5, 16);list.show();//10 12 13 14 15 16System.out.println(list.length());//6list.delete(2);list.show();//10 13 14 15 16list.delete(2);list.show();//10 14 15 16System.out.println(list.length());//4list.deleteHead();list.show();//14 15 16System.out.println(list.findByPos(2).data);//15System.out.println(list.findByPos(3).data);//16System.out.println(list.findByData(15).data);//15}}


0 0