链表是一种常见的数据结构,常用操作包括插入节点、删除节点、反转链表、合并有序链表等。
下面使用Java实现合并有序链表、就地逆置单链表、查找链表的中间节点和删除链表中的重复元素。
一、1. 链表节点类定义
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
this.next = null;
}
}
2. 合并有序链表
代码如下:
public class MergeSortedLinkedLists {
public static ListNode mergeSortedLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val < l2.val) {
l1.next = mergeSortedLists(l1.next, l2);
return l1;
} else {
l2.next = mergeSortedLists(l1, l2.next);
return l2;
}
}
}
3. 就地逆置单链表
public class ReverseLinkedList {
public static ListNode reverseLinkedList(ListNode head) {
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
}
4. 查找链表的中间节点
代码如下:
public class FindMiddleNode {
public ListNode findMiddle(ListNode head) {
if (head == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
5. 删除链表中的重复元素
代码如下:
public class RemoveDuplicates {
public ListNode removeDuplicates(ListNode head) {
ListNode current = head;
while (current != null && current.next != null) {
if (current.val == current.next.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}
}