如何用Java编写删除有序链表重复元素的方法?

2026-05-28 11:541阅读0评论SEO问题
  • 内容介绍
  • 相关推荐

本文共计301个文字,预计阅读时间需要2分钟。

如何用Java编写删除有序链表重复元素的方法?

给定向量表示的排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:输入:1-1-2输出:1-2

示例 2:输入:1-1-2-3-3输出:1-2-3

java/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val=x; } * } */class Solution { public ListNode deleteDuplicates(ListNode head) { if (head==null || head.next==null) return 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; }}

如何用Java编写删除有序链表重复元素的方法?

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

输入: 1->1->2
输出: 1->2
示例 2:

输入: 1->1->2->3->3
输出: 1->2->3

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null){ return head; } head.next = deleteDuplicates(head.next); if(head.val == head.next.val) head = head.next; return head; } }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

本文共计301个文字,预计阅读时间需要2分钟。

如何用Java编写删除有序链表重复元素的方法?

给定向量表示的排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:输入:1-1-2输出:1-2

示例 2:输入:1-1-2-3-3输出:1-2-3

java/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val=x; } * } */class Solution { public ListNode deleteDuplicates(ListNode head) { if (head==null || head.next==null) return 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; }}

如何用Java编写删除有序链表重复元素的方法?

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

输入: 1->1->2
输出: 1->2
示例 2:

输入: 1->1->2->3->3
输出: 1->2->3

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null){ return head; } head.next = deleteDuplicates(head.next); if(head.val == head.next.val) head = head.next; return head; } }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。