单链表的实现
学习内容:
单链表
单链表是一种链式存取的数据结构,用一组任意的存储单元存放线性表中的数据元素。链表中的数据是以结点表示的,每个结点由元素和指针组成。
在Java中我们可以将单链表定义成一个类,将单链表的基本操作定义为类中的方法,而每个结点即为类的实例化对象,每个对象中都有“元素值”和“下一个结点地址”两个属性,通过“下一个结点地址”这个属性来实现链表的链接.
单链表分为带头结点的单链表和不带头结点的单链表.
单链表虽然不能像顺序表那样实现随机存取,但单链表可以实现在任意位置插入或删除,不需要像顺序表那样需要移动大量元素才能完成,且单链表的地址是随机的,不一定是一段连续的空间.
public class Node{ private T value; private Node next; public Node() { } public Node(T value, Node next) { this.value = value; this.next = next; } }
像这样就是了一个简单的链表。
哪么如何来给链表添加元素呢?
头插法,
public Nodecreat(int n) {//创建20个 Node first = null; for (int i = 0; i < n; i++) { first = new Node<>((int) (Math.random() * 20 + 1), first); } return first; }
尾插法,尾插法插入的原理其实与头插法类似,只是尾插法需要先找到链表中的最后一个结点,之后直接将新建结点放到链表最后面即可.首先Node cur = head,让其遍历单链表,找到最后一个结点,之后直接return即完成了单链表的尾插法.
public Nodecreat(int n) {//创建20个 Node temp = new Node<>((int) (Math.random() * 20 + 1)); for (int i = 0; i < (n - 2); i++) { int x = (int) (Math.random() * 20 + 1); temp = new Node<>(x, temp); } return new Node<>((int) (Math.random() * 20 + 1), temp); }
遍历链表,利用while语句遍历一遍单链表即可.
public void print(Nodenode) { Node temp = node; while (temp != null) { System.out.print(temp.getValue() + " "); temp = temp.getNext(); } }
找出链表里相同的元素
public void samecell(Nodenode) { Node temp = node; int indexx = 0; while (temp != null) { int x = temp.getValue(); indexx++; int indexy = indexx; Node temp1 = temp.getNext(); while (temp1 != null) { indexy++; int y = temp1.getValue(); if (x == y) { System.out.println("第" + indexx + "位置和第" + indexy + "相同"); } temp1 = temp1.getNext(); } temp = temp.getNext(); } }
清空链表
public void clear(Nodenode) { node.setNext(null); node.setValue(null); }
删除链表里所有的指定的元素,并记录所剩的节点数
public void delect(Nodenode, int x) { int count = 0; while (node != null) { if (node.getValue() == x) { if (node.getNext() == null) { node.setValue(null); break; } System.out.println("删除了一个" + x); node.setValue(node.getNext().getValue()); node.setNext(node.getNext().getNext()); continue; } System.out.print(node.getValue() + " "); count++; node = node.getNext(); } System.out.println("链表还剩" + count); } }
将指定元素插入到第一次出现的最小元素前面
public void insertmin(Nodenode, int x) { Node temp = node; int a = temp.getValue(); while (temp != null) { if (a > temp.getValue()) { a = temp.getValue(); } temp = temp.getNext(); } while (node != null) { if (a == node.getValue()) { Node z = new Node<>(node.getValue(), node.getNext()); node.setValue(x); node.setNext(z); break; } node = node.getNext(); } }
将指定元素插入到第一次出现的最大元素后面
public void insertmax(Nodenode, int x) { Node temp = node; int a = temp.getValue(); while (temp != null) { if (temp.getValue() > a) { a = temp.getValue(); } temp = temp.getNext(); } while (node != null) { if (a == node.getValue()) { Node z = new Node<>(x, node.getNext()); node.setNext(z); break; } node = node.getNext(); } }



