public class Linklist<T> {
private class Node{
private T info;
private Node next;
public Node(T info,Node next){
this.info = info;
this.next = next;
}
}
private Node head;//头节点
private int size;//链表长度
//构造方法
public Linklist(Node head,int size){
this.head = head;
this.size = size;
}
public Linklist() {
}
/**
* 链表基础操作
*/
public int getSize(){
return this.size;
}
//向链表头节点前面添加一个节点,其数据域为info
public void addHead(T info){
this.head = new Node(info,head);
this.size++;
}
//尾插法
public void addLast(T info){
this.add(info,this.size);
}
//插入指定位置
public void add(T info,int index){
if(index < 0 || index > size) return;
else if(index == 0){
addHead(info);
return;
}
Node pre = this.head;//找到添加位置的前一个节点
for(int i = 0;i < index-1;i++){
pre = pre.next;
}
Node node = new Node(info,pre.next);
pre.next = node;
this.size++;
}
//删除任意位置的结点
public void delete(Node head,int index){
if(head == null) return;
if(index < 0 || index > size-1) return;
if(index == 0){
this.head = head.next;
}
Node front = this.head;//指向删除节点前面的节点
Node rear = this.head;//指向删除节点
for(int i = 0;i<index-1;i++){
front = front.next;
rear = rear.next;
}
rear = front.next;//指向删除节点
front.next = rear.next;
rear.next = null;
this.size--;
}
//查找元素,返回第一次出现的位置
public int search(T info){
if(this.head == null) return -1;
Node node = this.head;
for(int i = 0;i < this.size;i++){
if(node.info == info) return i;
node = node.next;
}
return -1;//没找到返回-1
}
//链表逆置
public void invert(Node head){
if(head == null) return;
else if(this.size == 1) return;
else {
Node begin,mid,end;//三指针,end用于判断什么时候结束,mid和begin用于翻转链表
begin = null;
mid = head;
end = head.next;
while(true){
mid.next = begin;
if(end == null) break;
begin = mid;
mid = end;
end = end.next;
}
this.head = mid;//将头节点重新定义
}
}
public void travel(Node h){
if(h == null) return;
while(h != null){
if(h.next != null){
System.out.print(h.info+ "->");
}
else{
System.out.print(h.info);
}
h = h.next;
}
System.out.println('\n');
}
public static void main(String[] args) {
Linklist<Integer> s = new Linklist<>();
for (int i = 0; i < 5; i++) {
s.addHead(i);
}
s.add(7,4);
System.out.println(s.search(3));
s.travel(s.head);
s.delete(s.head,4);
s.travel(s.head);
s.invert(s.head);
s.travel(s.head);
}
}
输出结果:
1
4->3->2->1->7->0
4->3->2->1->0
0->1->2->3->4