Java链表增删查改
爱打酱油的新一 人气:0一. 概念与结构
链表是一种物理存储结构上非连续存储结构,数据元素的逻辑顺序是通过链表中的引用链接次序实现的 。
虽然有这么多的链表的结构,但是我们重点掌握两种:
1.无头单向非循环链表:结构简单,一般不会单独用来存数据。实际中更多是作为其他数据结构的子结构,如哈希桶、图的邻接表等等。另外这种结构在笔试面试中出现很多。
2.无头双向链表:在Java的集合框架库中LinkedList底层实现就是无头双向循环链表。
二.单链表接口实现
接下来新一带大家写无头单向非循环链表
import java.util.List; /** * Created with IntelliJ IDEA. * Description: 链表 * User: mac * Date: 2022-08-31 * Time: 10:09 */ //ListNode代表一个节点 - 存放在一个节点类中 class ListNode { public int val; public ListNode next; public ListNode(int val) { this.val = val; } } public class MyLinkedList { public ListNode head;//链表的头引用 //打印链表 public void display() { //this.head.next != null 会丢失一个数据 ListNode cur = this.head; while (cur != null) { System.out.print(cur.val + " "); cur = cur.next; } System.out.println(); } //查找是否包含关键字k public boolean contains(int key) { ListNode cur = this.head; while (cur != null) { if (cur.val == key) { return true; } cur = cur.next; } return false; } //得到单链表的长度 public int size() { int count = 0; ListNode cur = this.head; while (cur != null) { count++; cur = cur.next; } return count; } //头插法 public void addFirst(int data){ //绑定位置的时候一定要先绑定后边 ListNode node = new ListNode(data); node.next = this.head; this.head = node; } //尾插法 public void addLast(int data){ ListNode node = new ListNode(data); if (this.head == null){//判空,否则就会造成引用异常this.head.next this.head = node; } else { ListNode cur = this.head; while (cur.next != null){ cur = cur.next; } //cur.next = null; cur.next = node; } } public ListNode findindex(int index){//通过下表来移动指针 ListNode cur = this.head; while (index - 1 != 0){ cur = cur.next; index--; } return cur; } //任意位置插入,第一个数据节点为0号下标 public void addIndex(int index, int data){ if (index < 0 || index > size()){ System.out.println("index位置不合法!"); return; } if (index == 0){ addFirst(data); return; } if (index == size()){ addLast(data); return; } ListNode cur = findindex(index); ListNode node = new ListNode(data); node.next = cur.next; cur.next = node; } //删除第一次出现的关键字为key的节点 public void remove(int key){ if (this.head == null){ System.out.println("单链表为空,不能删除!"); return; } if (this.head.val == key){//判断头部是否为目标节点 this.head = this.head.next; return; } ListNode cur = this.head; while (cur.next != null){ if (cur.next.val == key){ cur.next = cur.next.next; return; } cur = cur.next; } System.out.println("未找到该节点"); } //删除所有值为key的节点 public ListNode removeAllKey(int key){ if (this.head == null) return null; ListNode prev = this.head; ListNode cur = this.head.next; while (cur != null){ if (cur.val == key){ prev.next = cur.next; cur = cur.next; } else{ prev = cur; cur = cur.next; } } //最后处理头 if (this.head.val == key){ this.head = this.head.next; } return this.head; } //清空链表 public void clear(){ //this.head = null;//暴力解决 - 不推荐但没毛病 while (this.head != null){ ListNode curNext = this.head.next; this.head.next = null; this.head = curNext; } } }
加载全部内容