算法-----链表
来源:互联网 发布:淘宝商家客服 编辑:程序博客网 时间:2024/05/18 02:13
- package com.eshore.sweetop.dataframe;
- public class MyLinkedList {
- private Element head;
-
- public void insert(int x){
- Element e=new Element(x);
- e.next=head;
- if(head!=null){
- head.pre=e;
- }
- head=e;
- e.pre=null;
- }
-
- private Element search(int k){
- Element e=head;
- while(e!=null && e.key!=k){
- e=e.next;
- }
- return e;
- }
-
- private void delete(int x){
- Element e=search(x);
- if(e.pre!=null){
- e.pre.next=e.next;
- }else{
- head=e.next;
- }
- if(e.next!=null){
- e.next.pre=e.pre;
- }
- }
-
- public String toString(){
- StringBuilder sb=new StringBuilder();
- sb.append("[");
- Element e=head;
- while(e!=null){
- sb.append(e.key);
- sb.append(",");
- e=e.next;
- }
- sb.setCharAt(sb.length()-1, ']');
- return sb.toString();
- }
-
-
-
- private class Element{
- private Element pre;
- private Element next;
- public int key;
-
- public Element(int x){
- this.key=x;
- }
- }
-
-
- public static void main(String[] args) {
- MyLinkedList list=new MyLinkedList();
- list.insert(3);
- list.insert(6);
- list.insert(4);
- list.delete(6);
- System.out.println(list);
- }
-
- }