题目:
地址:https://leetcode.cn/problems/remove-duplicates-from-sorted-list/
方法一:
方法二:
package com.zy.leetcode.LeetCode_04;/*** @Author: zy* @Date: 2024-12-25-15:19* @Description: 删除排链表中的里复元素* 给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。*/
public class ListNode_04 {private int val;private ListNode_04 next;public ListNode_04(int val) {this.val = val;}public ListNode_04(int val, ListNode_04 next) {this.val = val;this.next = next;}public ListNode_04() {}/*** 构造一个方法,输入一个数组,然后初始化链表*/public static ListNode_04 initListNode(int[] arr) {ListNode_04 dummy = new ListNode_04(0);ListNode_04 cur = dummy;for (int num : arr) {cur.next = new ListNode_04(num);cur = cur.next;}return dummy.next;}/*** 删除链表中重复的元素* 1,2,3,3 -》1,2,3* 1,1,2,3 -》 1,2,3** @param node* @return*/public ListNode_04 deleteDulEnum(ListNode_04 node) {if (node == null || node.next == null) {return node;}ListNode_04 p1 = node;ListNode_04 p2 = node.next;while (p2 != null) {System.out.println("p1.val=" + p1.val);System.out.println("p2.val=" + p2.val);if (p2.val == p1.val) {p1.next = p2.next;} else {p1 = p2;}p2 = p2.next;}return node;}/*** 递归思想** @param node* @return*/private ListNode_04 getDulEnumList(ListNode_04 node) {//节点数小于2if (node == null || node.next == null) {return node;}ListNode_04 nextNode = node.next;node.next = getDulEnumList(nextNode);if (node.val == nextNode.val) {return node.next;} else {return node;}}public static void main(String[] args) {int[] ints = {1, 1, 2, 4, 5, 6};ListNode_04 listNode = ListNode_04.initListNode(ints);while (listNode != null) {System.out.print(listNode.val + " ,");listNode = listNode.next;}System.out.println("\n--------------------------------");ListNode_04 node = new ListNode_04().deleteDulEnum(ListNode_04.initListNode(ints));while (node != null) {System.out.print(node.val + " ");node = node.next;}System.out.println("--------------------------------");ListNode_04 node1 = new ListNode_04().getDulEnumList(ListNode_04.initListNode(ints));while (node1 != null) {System.out.print(node1.val + " ");node1 = node1.next;}}
}