题目
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
解答
解法一:非递归
代码中变量的含义:
-
pre 代表有效链表的最后一个位置。
-
p 是遍历指针,不断向前遍历链表。
如果 p 指向的结点的值与 pre 指向的结点的值相同,那么就直接跳过该结点避免重复。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode h = null;
ListNode pre = null;
ListNode p = head;
while(p != null) {
if(pre == null) {
h = p;
pre = p;
} else if(p.val != pre.val) {
pre.next = p;
pre = pre.next;
}
p = p.next;
}
// 清理一下脏结点
if(pre != null) pre.next = null;
return h;
}
}
结果
解法二:递归
具体为以下几步:
- 处理好递归终止条件 。
- 然后对后续结点递归。
- 如果 head 结点的值 与 后续结点递归后的新的头结点的值 相同,就去掉head。
代码
/**
* 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;
ListNode next = deleteDuplicates(head.next);
head.next = next;
return head.val == next.val ? next : head;
}
}