public class MySingList { //定义一个内部类 class Node{ public int val; public Node next; public Node(int val) { this.val = val; } } public Node head; public void createList(){ Node node1 =new Node(10); Node node2 =new Node(12); Node node3=new Node(14); Node node4=new Node(16); node1.next=node2; node2.next=node3; node3.next=node4; Node head=node1; } //头插法,就是在链表的头结点前面插入一个元素 public void addFirst(int data){ Node node= new Node(data); node.next=head; head=node; } //尾插法 public void addLast(int data){ Node node =new Node(data); Node cur=head; if(head==null){ head=node; return ; } while(cur.next!=null){ cur=cur.next; } cur.next=node; } //任意位置插入,第一个数据节点为0号下标 public void addIndex(int index, int data) throws IndexOutOfException{ Node node =new Node(data); //判断插入元素的下标是不是合法的 isVaildIndex(index); if(index==0) { addFirst(data); return; } if(index==size()){ addLast(data); return; } Node cur= findPlace(index); node.next=cur.next; cur.next=node; } //得找到走index-1步的地址 private Node findPlace(int index){ int count=0; Node cur=head; while(count!=index-1){ count++; cur=cur.next; } return cur; } private void isVaildIndex(int index) throws IndexOutOfException{ if(index<0||index>size()){ throw new IndexOutOfException("index位置不合法"); } } //查找是否包含关键字key是否在单链表当中 public boolean contains(int key){ Node cur=head; while(cur!=null){ if(cur.val==key){ return true; } cur=cur.next; } return false; } //删除第一次出现关键字为key的节点 public void remove(int key){ if(head==null){ return; } if(head.val==key){ head=head.next; return; } Node cur=findPlace1(key);//删除结点的前驱结点 if(cur==null){ return; } Node del=cur.next;//要删除的结点 cur.next=del.next;//完成删除了 } //找到key结点的前一个结点的地址 private Node findPlace1(int key){ Node cur=head; while(cur.next!=null){ if(cur.next.val==key){ return cur; } cur=cur.next; } return null; } //删除所有值为key的节点 public void removeAllKey(int key) { if (head == null) { return; } Node prev = head; Node cur = head.next; while (cur != null) { if (cur.val == key) { prev.next = cur.next; cur = cur.next; } else { prev = cur; cur = cur.next; } } if(head.val==key){ head=head.next; } } //得到单链表的长度 public int size(){ Node cur=head; int count=0; while (cur!=null){ count++; cur=cur.next; } return count; } public void display(){ Node cur=head; while (cur!=null){ System.out.println(cur.val+""); cur=cur.next; } } public void clear(){ head=null; } }
主要是删除和任意位置的增加比较困难,明天对这几个进行画图版的详解,敬请期待啊!!
886!!!