题目来源LeetCode
NO.83
给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
链表中节点数目在范围 [0, 300] 内
-100 <= Node.val <= 100
题目数据保证链表已经按升序 排列
通过次数533,182提交次数1,000,779
思路1(指针法):
由题知链表是升序的,故可以扫描链表比较相邻的两个元素,如果两者相等,则将指针后移(跳过相等的那个元素)
代码实现:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null){
return head;
}
ListNode currrent = head;
while(current!=null){
if(current.next.val == current.val){
current.next = current.next.next;
}else{current = current.next;}
}
return head;
}
}
思路2:递归法
(问题规模不断变小,解决问题的方式没变)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
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;
}
}