数据结构与算法
1. 什么是单链表
单链表是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。链表中的数据是以结点来表示的,每个结点的构成:元素(数据元素的映象) + 指针(指示后继元素存储位置),元素就是存储数据的存储单元,指针就是连接每个结点的地址数据。
2. 实现单链表的增删操作
1. 插入单链表第i个结点,即插入到ai-1与ai之间的具体步骤:
- 找到 ai-1 的引用 p
- 生成一个数据域为 x 的新结点 s
- 设置p.next = s
- 设置s.next = ai
2. 删除第i个结点
- 找到ai-1的存储位置p
- p.next指向ai的直接后继结点ai+1
代码示例:
/**
* 描述: Java对链表的一些操作
*
* @author Ye
* @version 1.0
* @date 2021/8/17 17:06
*/
public class MyLinkedList {
/**
* 链表头的引用
* */
Node head = null;
/**
* 向链表中插入数据
* @param data: 插入数据的内容
* */
public void addNode(int data){
Node newNode = new Node(data);
if (head == null){
head = newNode;
return;
}
Node temp = head;
while (temp.next != null){
temp = temp.next;
}
temp.next = newNode;
}
/**
* @param index: 删除第index个结点
* @return 成功返回true,失败返回false
* */
public Boolean deleteNode(int index){
if (index < 1 || index > length()){
return false;
}
if (index == 1){
head = head.next;
return true;
}
int i = 2;
Node preNode = head;
Node curNode = preNode.next;
while (curNode != null){
if (i == index){
preNode.next = curNode.next;
return true;
}
preNode = curNode;
curNode = curNode.next;
i++;
}
return true;
}
/**
* @return 返回结点的长度
* */
public int length(){
int length = 0;
Node temp = head;
while (temp != null){
length ++;
temp = temp.next;
}
return length;
}
/**
* 对链表进行排序
* 返回排序后的头结点
* */
public Node orderList(){
Node nextNode = null;
int temp = 0;
Node curNode = head;
while (curNode != null){
nextNode = curNode.next;
while (nextNode != null){
if (curNode.data > nextNode.data){
temp = curNode.data;
curNode.data = nextNode.data;
nextNode.data = temp;
}
nextNode = nextNode.next;
}
curNode = curNode.next;
}
return head;
}
public void printList(){
Node temp = head;
while (temp != null){
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.addNode(95);
list.addNode(56);
list.addNode(84);
list.addNode(44);
list.addNode(67);
list.addNode(45);
list.addNode(58);
list.addNode(94);
list.addNode(14);
list.addNode(7);
System.out.println("链表长度为: " + list.length());
System.out.print("排序前: ");
list.printList();
list.orderList();
System.out.print("排序后: ");
list.printList();
System.out.println("删除第三个结点后:");
list.deleteNode(3);
list.printList();
}
}
/**
* 结点类
*
* */
class Node{
Node next = null;
int data;
public Node(int data){
this.data = data;
}
}
运行截图:
3. 删除链表的重复数据
从链表中删除重复数据,可以遍历链表,把遍历到的值存储到一个hashtable,在遍历过程中,若当前访问的值在hashtable中已经存在,则说明这个数据是重复的,因此可以删除。
代码如下:
/**
* 删除单链表的重复数据
* @param head:单链表的头指针
* */
public void deleteDuplecate(Node head){
Hashtable<Integer,Integer> table = new Hashtable<>();
Node temp = head;
Node pre = n