1.题目要求
给定一个已排序的链表的头 head
, 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
示例 1:
输入:head = [1,1,2] 输出:[1,2]
示例 2:
输入:head = [1,1,2,3,3] 输出:[1,2,3]
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 || head.next == null){
return head;
}
//定义两个指针
ListNode fir = head;
ListNode sec = head.next;
while(sec != null){
//如果两个指针的值相等,则fir不动sec= src.next
if(fir.val == sec.val){
//否则fir = fir.next然后把sec的值传给fir
}else{
fir = fir.next;
fir.val = sec.val;
}
sec = sec.next;
}
//最后把fir.next指向空
fir.next = null;
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删除成符合题目要求的链表
//此时只需要判断head与head.next是否相等即可
head.next = deleteDuplicates(head.next);
return head.val == head.next.val?head.next:head;
}
}