public class MyLinkedList<T> {
private Node head;
private int size;
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
public void setSize(int size) {
this.size = size;
}
class Node<T> {
private T t;
private Node next;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node(T t, Node next) {
this.t = t;
this.next = next;
}
public Node() {
}
@Override
public String toString() {
if(this==head.next){
return "LinkedList{"+this.t;
}
if(this.next==null){
return this.t+"}";
}
return " "+this.t+" ";
}
}
public MyLinkedList(){
head=new Node(null,null);
size=0;
}
public int getSize(){
return size;
}
public boolean isEmpty(){
return size==0;
}
public void add(T t){
if(size==0){
head.next=new Node(t,null);
}
else{
Node n=head;
while (n.next!=null){
n=n.next;
}
n.next=new Node(t,null);
}
size++;
}
public T getByIndex(int index){
if(index>size-1){
throw new IndexOutOfBoundsException();
}
Node n=head;
for(int i=0;i<index;i++){
n=n.next;
}
return (T) n.t;
}
public MyLinkedList reverse(){
Node[] arr=new Node[this.size];
Node node=this.head.next;
int index=arr.length-1;
while (node!=null){
arr[index--]=node;
node=node.next;
}
Node head=new Node(null,null);
Node node1=head;
for(int i=0;i<arr.length;i++){
node1.next=arr[i];
node1=node1.next;
}
this.setHead(head);
return this;
}
public void addFirst(T t){
if(size==0){
head.next=new Node(t,null);
}
else {
head.next=new Node(t,head.next);
}
size++;
}
public void addByIndex(T t,int index){
if(index>size-1){
throw new IndexOutOfBoundsException();
}
Node n=head.next;
for(int i=0;i<index-1;i++){
n=n.next;
}
n.next=new Node(t,n.next);
size++;
}
public boolean remove(T t) throws Exception {
if(t==null){
throw new NullPointerException();
}
Node n=head;
while (true){
if(n.next.t==t){
Node mid=n.next;
n.next=mid.next;
size--;
mid.next=null;
return true;
}
if(n.next==null){
return false;
}
n=n.next;
}
}
public T removeByIndex(int index){
if(index>size-1){
throw new IndexOutOfBoundsException();
}
Node n=head.next;
for(int i=0;i<index-1;i++){
n=n.next;
}
Node mid=n.next;
n.next=mid.next;
size--;
T t= (T) mid.t;
mid.next=null;
return (T) t;
}
public void bianLi(){
Node n=head;
for(int i=0;i<size;i++){
System.out.print(n.next+" ");
n=n.next;
}
}
public boolean contain(T t) throws Exception {
if(t==null){
throw new NullPointerException();
}
else {
Node n=head;
while (head!=null){
if(head.t==t){
return true;
}
head=head.next;
}
return false;
}
}
}