题目描述
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例
输入: 1->1->2
输出: 1->2
输入: 1->1->2->3->3
输出: 1->2->3
解题思路
1.双指针一次扫描
java代码如下:
public class Solution {
private class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode deleteDuplicates(ListNode head) {
ListNode dummyNode = new ListNode(Integer.MIN_VALUE);
dummyNode.next = head; //设置虚拟头结点
ListNode pre = dummyNode;//前后指针
ListNode cur = head;
ListNode relNode;
while (cur != null){
if(cur.val == pre.val){ //删除cur指向节点
relNode = cur;
pre.next = relNode.next;
relNode.next = null; //方便JVM回收
cur = pre.next;
}else { //向前遍历
pre = pre.next;
cur = cur.next;
}
}
head = dummyNode.next;
dummyNode.next = null;//方便JVM回收
return head;
}
}
运行结果如下:
2.运用链表的天然递归性质
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) {
return null;
}
if (head.next == null) {
return head;
}
if (head.val == head.next.val) {
head = deleteDuplicates(head.next);
} else {
head.next = deleteDuplicates(head.next);
}
return head;
}
}
运行结果如下: