public class LinkList {
/**
* @author yhd
* @email
* @description 节点
* @params
* @return
* @since 2021/4/1 16:22
*/
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
public Node() {
}
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
//声明头结点,尾结点
Node head, tail;
{
tail = head = new Node();
}
/**
* @return
* @author yhd
* @email
* @description 头插法
* @params
* @since 2021/4/1 16:27
*/
public void insertFromHead(int data) {
if (head == tail) {
insertFromTail(data);
return;
}
head.next = new Node(data, head.next);
}
/**
* @return
* @author yhd
* @email
* @description 尾插法
* @params
* @since 2021/4/1 16:29
*/
public void insertFromTail(int data) {
tail = tail.next = new Node(data);
}
/**
* @return
* @author yhd
* @email
* @description 返回链表中节点个数
* @params
* @since 2021/4/1 16:32
*/
public int getTotal() {
Node point = head;
//*-- 1--2--3
int total = 0;
while (point.next != null) {
total++;
point = point.next;
}
return total;
}
/**
* @return
* @author yhd
* @email
* @description 在单链表第i个元素之前插入一个元素
* @params
* @since 2021/4/1 16:39
*/
public void insertDataAt(int i, int data) {
Node point = head;
for (int j = 1; j < i; j++) {
if (point == null) {
return;
}
point = point.next;
}
if (tail == point) {
insertFromTail(data);
return;
}
point.next = new Node(data, point.next);
}
/**
* @return
* @author yhd
* @email
* @description 删除单链表中某节点的后继节点
* @params
* @since 2021/4/1 17:36
*/
public void remove(Node node) {
if (node != null && node.next != null) {
node.next = node.next.next;
}
}
/**
* @return
* @author yhd
* @email
* @description 按值查找
* @params
* @since 2021/4/1 17:57
*/
public Node searchNodeByData(int data) {
Node point = head;
while (point.next != null) {
if (point.next.data == data) {
return point.next;
}
}
return null;
}
/**
* @return
* @author yhd
* @email
* @description 读取单链表中第i个元素
* @params
* @since 2021/4/1 18:51
*/
public Node searchNodeByIndex(int index) {
Node p = head;
int count = 0;
while (p.next != null) {
count++;
p = p.next;
if (count == index) {
return p;
}
}
return null;
}
/**
* @return
* @author yhd
* @email
* @description 链表反转
* @params
* @since 2021/4/1 17:50
*/
public void reverse() {
if (head.next != null) {
tail = travel(head.next);
tail.next = null;
}
}
private Node travel(Node node) {
//如果node是尾结点
if (node.next == null) {
//将head指向node
head.next = node;
//返回node
return node;
}
//否则,接续递归
travel(node.next).next = node;
//返回node
return node;
}
}
单链表
最新推荐文章于 2024-07-15 22:10:26 发布