算法-----链表

来源:互联网 发布:淘宝商家客服 编辑:程序博客网 时间:2024/05/18 02:13
  1. package com.eshore.sweetop.dataframe;
  2. public class MyLinkedList {
  3.     private Element head;
  4.     
  5.     public void insert(int x){
  6.         Element e=new Element(x);
  7.         e.next=head;
  8.         if(head!=null){
  9.             head.pre=e;
  10.         }
  11.         head=e;
  12.         e.pre=null;
  13.     }
  14.     
  15.     private Element search(int k){
  16.         Element e=head;
  17.         while(e!=null && e.key!=k){
  18.             e=e.next;
  19.         }
  20.         return e;
  21.     }
  22.     
  23.     private void delete(int x){
  24.         Element e=search(x);
  25.         if(e.pre!=null){
  26.             e.pre.next=e.next;
  27.         }else{
  28.             head=e.next;
  29.         }
  30.         if(e.next!=null){
  31.             e.next.pre=e.pre;
  32.         }
  33.     }
  34.     
  35.     public String toString(){
  36.         StringBuilder sb=new StringBuilder();
  37.         sb.append("[");
  38.         Element e=head;
  39.         while(e!=null){
  40.             sb.append(e.key);
  41.             sb.append(",");
  42.             e=e.next;
  43.         }
  44.         sb.setCharAt(sb.length()-1']');
  45.         return sb.toString();
  46.     }
  47.     
  48.     
  49.     
  50.     private class Element{
  51.         private Element pre;
  52.         private Element next;
  53.         public int key;
  54.         
  55.         public Element(int x){
  56.             this.key=x;
  57.         }
  58.     }
  59.     
  60.     
  61.     public static void main(String[] args) {
  62.         MyLinkedList list=new MyLinkedList();
  63.         list.insert(3);
  64.         list.insert(6);
  65.         list.insert(4);
  66.         list.delete(6);
  67.         System.out.println(list);
  68.     }
  69.     
  70. }