83. 删除排序链表中的重复元素

题目

存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素只出现一次

返回同样按升序排列的结果链表。

/**
 * @author chenzufeng
 * @date 2021-06-27
 * 单链表
 */
public class SinglyLinkedListNode {
    int value;
    SinglyLinkedListNode nextNode;

    SinglyLinkedListNode() {}

    SinglyLinkedListNode(int value) {
        this.value = value;
    }

    SinglyLinkedListNode(int value, SinglyLinkedListNode nextNode) {
        this.value = value;
        this.nextNode = nextNode;
    }
}

解题思路

由于给定的链表是排好序的,重复的元素在链表中出现的位置是连续的,因此只需要对链表进行一次遍历,就可以删除重复的元素。

具体地,指针\(\textit{cur}\) 指向链表的头节点,随后开始对链表进行遍历。如果当前 \(\textit{cur}\)\(\textit{cur.next}\) 对应的元素相同,那么就将 \(\textit{cur.next}\) 从链表中移除;否则说明链表中已经不存在其它与 \(\textit{cur}\) 对应的元素相同的节点,因此可以将 \(\textit{cur}\) 指向 \(\textit{cur.next}\)

当遍历完整个链表之后,返回链表的头节点即可。

代码实现

/**
 * @author chenzufeng
 * @date 2021-07-11
 * 83. 删除排序链表中的重复元素
 */
public class No83_RemoveDuplicatesFromSortedList {
    public SinglyLinkedListNode removeDuplicatesFromSortedList(SinglyLinkedListNode head) {

        if (head == null) {
            return null;
        }

        SinglyLinkedListNode currentNode = head;
        while (currentNode.nextNode != null) {
            if (currentNode.value == currentNode.nextNode.value) {
                currentNode.nextNode = currentNode.nextNode.nextNode;
            } else {
                currentNode = currentNode.nextNode;
            }
        }

        return head;
    }
}

复杂度分析

  • 时间复杂度:\(O(N)\),其中 \(n\) 是链表的长度。
  • 空间复杂度:\(O(1)\)
posted @ 2021-07-11 18:54  chenzufeng  阅读(217)  评论(0)    收藏  举报