自定义实现单链表
对单链表实现类增-删的基本操作
package com.briup.algorithm.LinkedList; public class MyLinkedList{ //内部类定义节点 也可以放在外面 因为我把把节点当成一个成员 所以用内部类实现 private class Node{ public T date; Node next; public Node(T t){ this(t,null); } public Node(T t, Node next){ this.date=t; this.next=next; } } //定义一个头节点 private Node head;//头节点 private int size;//链表元素个数 //对单链表初始化 public MyLinkedList(){ this.head=null; size=0; } // 获取链表元素的个数 public int getSize(){ return size; } // 判断链表是否为空 public boolean isEmpty(){ return this.size==0; } // 链表头部添加元素 public void addHead(T t){ Node newNode = new Node(t); newNode.next=this.head; this.head=newNode; //this.head=new Node(t,head) size++; } // 向链表尾部插入元素 public void addTail(T t){ add(t,this.size); } // 向链表中间插入元素 public void add(T t,int index){ if (index < 0 || index > size) { throw new IllegalArgumentException("index is error"); } if (index==0){ addHead(t); return; } //找到要插入的前一个节点 Node newNodePre = this.head; for (int i = 0; i < index-1; i++) { newNodePre = newNodePre.next; } Node newNode = new Node(t); newNode.next=newNodePre.next; newNodePre.next=newNode; this.size++; } // 删除链表元素 public void remove(T t) { if (head == null) { System.out.println("无元素可删除"); return; } // 要删除的元素与头结点的元素相同 while (head != null && head.date.equals(t)) { head = head.next; } this.size--; Node cur = this.head; while (cur != null && cur.next != null) { if (cur.next.date.equals(t)) { this.size--; cur.next = cur.next.next; } else{cur = cur.next; } } } // 删除链表第一个元素 public void removeFirst(){ if (this.head == null) { System.out.println("无元素可删除"); return; } Node deleteNode = this.head; this.head = this.head.next; deleteNode.next=null; this.size--; } // 删除链表的最后一个元素 public void removeLast(){ if (this.head == null) { System.out.println("无元素可删除"); return; } if (this.getSize()==1){ removeFirst(); } //存储倒数第二个节点 Node LastNodePre = this.head;//先从头节点找 //判断这个节点的下下个节点是否是空 是的话就这个节点的下个节点存起来存起来 while (LastNodePre.next.next!=null){ LastNodePre=LastNodePre.next; } LastNodePre.next=null; this.size--; } // 链表中是否包含某个元素 public boolean contain(T t){ Node cur = this.head; while (cur!=null){ if (cur.date.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.date + "->"); cur = cur.next; } sb.append("NULL"); return sb.toString(); } public static void main(String[] args) { MyLinkedList list = new MyLinkedList (); for (int i = 0; i < 10; i++) { list.addHead(i); } System.out.println(list.contain(33)); System.out.println(list); list.add(33,0); list.add(33,5); list.addTail(33); System.out.println(list); System.out.println(list.contain(33)); list.removeFirst(); System.out.println(list); list.removeLast(); System.out.println(list); list.remove(33); System.out.println(list); } }



