1.题目描述:
存在一个按升序排列的链表,给你这个链表的头节点head,请你删除所有重复的元素,使每个元素只出现一次。返回同样按升序排列的结果链表。
2.双指针遍历:
遍历链表,找到最后出现的重复元素的后一节点置为temp.next即可,思路直接见代码和图解,刚写出来的代码比较繁琐,优化时发现几行代码功能重复了,最后自己写的代码提交成功结果不错,有点小开心。
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode temp = head;
ListNode loopTemp = temp;
boolean flag = false;
while(temp != null){
while(loopTemp.next != null && loopTemp.val == loopTemp.next.val){
loopTemp = loopTemp.next;
flag = true;
}
if(flag) temp.next = loopTemp.next;//跳过重复元素,存在loopTemp.next为null的情况
temp = temp.next;//大循环后移
loopTemp = temp;//每次保证两个指针在同一个位置
}
return head;
}
}
3.单次循环遍历:比我简单不少,官解还是牛啊。。。
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return head;
}
ListNode cur = head;
while (cur.next != null) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}
4.递归:直接看代码。。。
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;//从后往前拼接
}
}