注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
代码1:简洁易懂
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode list = head;
while (list != null) {
if (list.next == null) break;
if (list.val == list.next.val)
list.next = list.next.next;
else list = list.next;
}
return head;
}
}
代码2:递归
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) return head;
head.next = deleteDuplicates(head.next);
return head.val == head.next.val ? head.next : head;
}
}
本文提供两种方法实现从已排序链表中删除所有重复元素,确保每个元素仅出现一次。方法一采用迭代方式,通过遍历链表并比较相邻节点值来移除重复项;方法二是递归方案,同样能达到相同效果。
711

被折叠的 条评论
为什么被折叠?



