逢三退一小程序源码 双向链表实现

来源:互联网 发布:做汉化的软件 编辑:程序博客网 时间:2024/06/06 09:08
package com.zx.juc;/** * Created by Administrator on 2017/5/7 0007. */public class ThreeToOne {    public static void main(String[] args){        LinkNode linkNode=new LinkNode();        for(int i=0;i<6;i++){            Node node=new Node(i);            linkNode.add(node);        }        int count=0;        System.out.println(linkNode.getNode().getObj());    }}class Node{    private Node prev;    private Node next;    private Object obj;    public Node(Object obj){        this.obj=obj;    }    public Node getPrev() {        return prev;    }    public void setPrev(Node prev) {        this.prev = prev;    }    public Node getNext() {        return next;    }    public void setNext(Node next) {        this.next = next;    }    public Object getObj() {        return obj;    }    public void setObj(Object obj) {        this.obj = obj;    }}class LinkNode {    private Node first;    private Node last;    public Node getFirst() {        return first;    }    public void setFirst(Node first) {        this.first = first;    }    public Node getLast() {        return last;    }    public void setLast(Node last) {        this.last = last;    }    public void add(Node node){        if(first==null){            first=last=node;        }        else {            Node oldLast=last;            last.setNext(node);            node.setPrev(last);            last=node;            last.setNext(first);            first.setPrev(last);        }    }    public void del(Node node){        if(node==first){            Node newFirst=first.getNext();            newFirst.setPrev(last);            last.setNext(newFirst);            first=newFirst;        } else if (node==last) {            Node newLast=last.getPrev();            newLast.setNext(first);            first.setPrev(newLast);            last=newLast;        } else {            Node curr=first;            while (curr!=node){                curr=curr.getNext();                if(curr==node) {                    Node prev=curr.getPrev();                    Node next=curr.getNext();                    prev.setNext(next);                    next.setPrev(prev);                    break;                }            }        }    }    public Node getNode(){        int count=0;        Node node=first;        while (node!=null){            if(first==last){                break;            }            count++;            if(count==3){                count=0;                del(node);                System.out.println("del-->"+node.getObj());            }            node=node.getNext();        }        return node;    }}

0 0
原创粉丝点击