package com.important.data.struct.LinkedListSingle;
public class SingleLinkedList
{
public static void main(String[] args)
{
SingleLinkedListType<String> singleLinkedListType = new SingleLinkedListType<>();
for(int i=0;i<5;i++){
String temp = i+"";
singleLinkedListType.add(temp);
}
System.out.println("单链表的大小: ");
System.out.println(singleLinkedListType.size());
System.out.println("单链表为:");
singleLinkedListType.println();
singleLinkedListType.reverse();
System.out.println("链表反转之后的链表为: ");
singleLinkedListType.println();
}
}
class SingleLinkedListType<T>{
private static class Node<T>{
public T date;
Node<T> next;
@SuppressWarnings("unused")
public Node(T d,Node<T> n){
date = d;
next = n;
}
public Node(T d){
date = d;
next = null;
}
}
private int theSize;
private Node<T> head;
public SingleLinkedListType()
{
clear();
}
public void clear(){
theSize = 0;
head = null;
}
public int size(){
return theSize;
}
public void add(T x){
Node<T> newNode = new Node<T>(x);
if(head == null){
head = newNode ;
}else {
Node<T> pNode = head;
while(pNode.next!=null){
pNode = pNode.next;
}
pNode.next = newNode;
}
theSize++;
}
public void add(int index ,T x){
checkRange(index);
Node<T> pNode = getNode(index);
Node<T> newNode = new Node<T>(x);
newNode.next = pNode.next;
pNode.next = newNode;
theSize++;
}
public void addFirst(T x){
Node<T> newNode = new Node<T>(x);
newNode.next = head;
head =newNode;
theSize++;
}
public void checkRange(int index){
if (index<0 || index > size())
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size();
}
public T get(int index){
Node<T> pNode = getNode(index);
return pNode.date;
}
public Node<T> getNode(int index){
checkRange(index);
Node<T> pNode = head;
for(int i=0;i<index;i++){
pNode = pNode.next;
}
return pNode;
}
public void removeTail(){
remove(size()-1);
theSize--;
}
public void remove(int index){
checkRange(index);
Node<T> pNode = getNode(index);
Node<T> temp = head;
for(int i=0;i<index-1;i++){
temp = temp.next;
}
temp.next = pNode.next;
pNode.next = null;
theSize--;
}
public void println(){
Node<T> pNode = head;
while(pNode!=null){
System.out.print(pNode.date+" ");
pNode = pNode.next;
}
System.out.println();
}
public void reverse(){
Node<T> pre = head;
Node<T> curr = head.next;
Node<T> next ;
while(curr!=null){
next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
head.next = null;
head = pre;
}
}