LeetCode 82:删除排序链表中的重复元素 II
题目:
方法一:
方法二:
代码示例
package com.zy.leetcode.LeetCode_82;
/**
* @Author: zy
* @Date: 2024-12-26-10:51
* @Description:
* .删除排序链表中的重复元素 II
*/
public class ListNode_82 {
private int val;
private ListNode_82 next;
public ListNode_82(int val, ListNode_82 next) {
this.val = val;
this.next = next;
}
public ListNode_82() {
}
public ListNode_82(int val) {
this.val = val;
}
/**
* 构造一个方法,输入一个数组,然后初始化链表
*/
public static ListNode_82 initListNode(int[] arr) {
ListNode_82 dummy = new ListNode_82(0);
ListNode_82 cur = dummy;
for (int num : arr) {
cur.next = new ListNode_82(num);
cur = cur.next;
}
return dummy.next;
}
private void print(ListNode_82 node) {
while (node != null) {
System.out.print(node.val + " -> ");
node = node.next;
}
}
/**
* 递归
*
* @param node
* @return
*/
private ListNode_82 deleteDuplicateNode(ListNode_82 node) {
//临界条件判断
if (node == null || node.next == null) {
return node;
}
if (node.val == node.next.val) {
// 找到第一个与下一个值不等的节点
while (node.next != null && node.val == node.next.val) {
node.next = node.next.next;
}
return deleteDuplicateNode(node.next);
} else {
node.next = deleteDuplicateNode(node.next);
return node;
}
}
private ListNode_82 deleteDuplicateNode2(ListNode_82 node) {
//临界条件判断
if (node == null || node.next == null) {
return node;
}
ListNode_82 s = new ListNode_82(-1, node);
ListNode_82 p1 = s;
ListNode_82 p2, p3;
while ((p2 = p1.next) != null && (p3 = p2.next) != null) {
if (p2.val == p3.val) {
while ((p3 = p3.next) != null && (p2.val == p3.val)) {
//不做操作
}
//找到了不相等的位置
p1.next = p3;
} else {
p1 = p1.next;
}
}
return s.next;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 3, 4, 4, 5};
ListNode_82 head = initListNode(arr);
System.out.print("原始链表:");
head.print(head);
System.out.println();
ListNode_82 result = new ListNode_82().deleteDuplicateNode(head);
System.out.print("删除后链表1:");
result.print(result);
System.out.println();
ListNode_82 result1 = new ListNode_82().deleteDuplicateNode(head);
System.out.print("删除后链表2:");
result.print(result1);
}
}