/**
* @create: 2021.4.13
*/
public class MyLinked<T> {
// 链表存储结点
private class Node{
private T t;
private Node next;
public Node(T t, Node next) {
this.t = t;
this.next = next;
}
public Node(T t) {
this(t,null);
}
}
// 链表头结点
private Node head;
// 链表元素个数
private int size;
// 链表构造
public MyLinked() {
this.head = null;
this.size = 0;
}
// 头插入
public void addFirst(T t){
Node node = new Node(t);
node.next = this.head;
this.head = node;
this.size++;
}
// 尾插,相当于在size位置插入
public void add(T t){
this.add(t,size);
}
// 在链表中插入
public void add(T t,int index){
if (index < 0 || index > size){
System.out.println("错误");
}
if (index == 0){
this.addFirst(t);
return;
}
Node pre = this.head;
// 找到要插入位置的前一个结点
for (int i = 0;i < index-1;i++){
pre = pre.next;
}
Node node = new Node(t);
// 新结点的后继节点指向前原前结点的后继结点
node.next = pre.next;
// 前结点的后继结点指向新结点
pre.next = node;
this.size++;
}
// 删除,无返回值
public void remove(T t){
if (head==null){
System.out.println("无元素");
return;
}
// 删除头结点
while (head!=null&&head.t.equals(t)){
head = head.next;
this.size--;
}
// 删除头结点以外
Node cur = this.head;
while (cur!=null&& cur.next!=null){
if (cur.next.t.equals(t)) {
this.size--;
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
}
// 删除头结点并返回值
public T removeFirst(){
if (this.head == null){
System.out.println("kong");
return null;
}
Node delNode = this.head;
this.head = this.head.next;
delNode.next = null;
this.size--;
return delNode.t;
}
// 删除尾结点并返回值
public T removeLast(){
if (this.head ==null){
System.out.println("kong");
return null;
}
if (this.size == 1){
return this.removeFirst();
}
Node cur = this.head;//当前节点
Node pre = this.head;//要删除结点的前一个结点
while (cur.next!=null){
pre = cur;
cur = pre.next;
}
// 要删除结点前一个结点的next指向当前结点的下一个null
pre.next = cur.next;
this.size--;
return cur.t;
}
// 链表中是否包含
public boolean contains(T t){
Node cur = this.head;
while (cur.next!= null){
if (cur.t.equals(t)){
return true;
}
else {
cur = cur.next;
}
}
return false;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
Node cur = this.head;
while(cur != null){
sb.append(cur.t+"->");
cur = cur.next;
}
sb.append("null");
return sb.toString();
}
public static void main(String[] args) {
MyLinked<Integer> linked = new MyLinked();
for (int i = 0; i < 10; i++) {
linked.addFirst(i);
System.out.println(linked);
}
linked.add(12);
System.out.println(linked);
linked.add(88,3);
System.out.println(linked);
linked.remove(4);
System.out.println(linked);
System.out.println(linked.removeFirst());
System.out.println(linked.contains(88));
System.out.println(linked.removeLast());
}
}
Java实现单链表
最新推荐文章于 2024-06-16 22:47:03 发布