题目描述
存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。
返回同样按升序排列的结果链表。
题解
双指针法
定义前指针pre,后指针cur(要删除的位置),双指针一起移动,如果pre和cur不相等,一起右移。如果pre和cur相等,删除cur节点。
(删除节点:假设cur的next命名为next节点,把前指针pre指向next节点,再把cur指向null空值,就删除成功了。删完记得更新cur的位置,把cur指向next处。)
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:38 MB, 在所有 Java 提交中击败了35.91%的用户
/**
* 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 pre = head;
ListNode cur = head.next;
while (pre != null && cur != null) {
if (pre.val != cur.val) {
pre = pre.next;
cur = cur.next;
}
else {
ListNode next = cur.next;
cur.next = null;
pre.next = next;
cur = next;
}
}
return head;
}
}