双向循环链表(插入,删除,就地逆置)

package design;

import java.util.Scanner;

//循环双链表
public class LinkedList  {
    private int theSize;
    private Node beginMarker;
    private Node endMarker;
    
	    class Node{          //定义匿名类Node
		public AnyType data;
		public Node prev;
		public Node next;
		public Node(AnyType d,Node p,Node n){
			this.data=d;
			this.prev=p;
			this.next=n;
		}
		
	}
	
	public LinkedList(){                         //构造方法
		beginMarker=new Node(null,endMarker,endMarker);
		endMarker=new Node(null,beginMarker,beginMarker);
		beginMarker.next=endMarker;
		theSize=0;
	}
	public int size(){                     
		return theSize;
	}
	public Node getNode(int idx){             //返回idx对应的结点
		Node p=null;
		if(idx<0||idx>size())
            System.out.println("无法找到该点");
		
		if(idxidx;i--)
				p=p.prev;
		}
	
		 return p;	    
	}
	
	public boolean add(AnyType x){     //插入元素
		add(size(),x);
		return true;
	}
	private void add(int idx,AnyType x){
		if(idx>size()||idx<0){
			System.out.println("输入错误");
		}else{
		Node p;
		p=getNode(idx);
		Node newNode=new Node(x,p.prev,p);
		newNode.prev.next=newNode;
		p.prev=newNode;
		theSize++;
		}
	}
	public AnyType remove(int idx){              //删除元素
		if(idx>size()||idx<0){
			System.out.println("无法找到该节点");
			return null;
		}else
		return remove(getNode(idx));
	}
	public AnyType remove(Node p){
		p.next.prev=p.prev;
		p.prev.next=p.next;
		theSize--;
		return p.data;
	}
	public void addFirst(AnyType data){
		add(0,data);
	}
	public void addLast(AnyType data){
		add(size(),data);
	}
	public void trs(){
	     Node p=beginMarker;
	     while(p.next!=beginMarker){
	    	 Node q=p;
	    	 Node r=p.next;
	    	 q.next=q.prev;
	    	 q.prev=r;
	    	 p=p.prev;
	     }
	     Node q=p;
	     Node r=p.next;
	     q.next=q.prev;
	     q.prev=r;
	     Node s=beginMarker;
	     beginMarker=endMarker;
	     endMarker=s;
	     
	     int i=0;
	     for(Node x=beginMarker.next;x!=endMarker;x=x.next){
	    	 System.out.println(i+": "+x.data);
	    	 i++;
	     }
	     i=0;
	}
	public void print(){
		int i=0;
		for(Node x=beginMarker.next;x.next!=beginMarker;x=x.next){
			System.out.println(i+": "+x.data);
			i++;
		}
		i=0;
	}
	public static void main(String[] args) {
	      //验证部分
		LinkedList La=new LinkedList();
		System.out.println("1:创建链表");
		System.out.println("2:添加结点");
		System.out.println("3:删除结点");
		System.out.println("4:添加第一个");
		System.out.println("5:添加最后一个");
		System.out.println("6 :转置");
		System.out.println("请输入要进行的操作");
		Scanner sc=new Scanner(System.in);
		boolean flag=true;
		while(flag){
			  System.out.println("请输入您的要进行的操作:");
			int c=sc.nextInt();
			switch(c){
			   case 1: System.out.println("请输入数据个数");
			           int n=sc.nextInt();
			           System.out.println("输入数据");
			           for(int i=0;i

你可能感兴趣的:(双向循环链表(插入,删除,就地逆置))