1
头图

Niuke.com High-Frequency Algorithm Question Series-BM15-Deleting Duplicate Elements in an Ordered Linked List-I

Topic description

Delete the duplicate elements in the given linked list (the elements in the linked list are ordered from small to large), so that all elements in the linked list appear only once

See the original title: BM15 delete duplicate elements in an ordered list -I

Solution 1: Linked List Traversal

First, consider the special case. If the linked list is empty or has only one node, there will be no duplicate elements, and the original linked list will be returned.

Otherwise, traverse the linked list nodes to determine whether there are duplicate elements. The processing process is as follows:

  • Use pre to record the last unrepeated node and initialize it as the head of the linked list;
  • Then traverse the linked list nodes from the second node next of the linked list;
  • If the values of next and pre are the same, delete the current duplicate node;
  • If the values of next and pre are not the same, update the value of pre.

After the traversal is completed, the head node of the linked list has not changed, just return to the head node.

code

 public class Bm015 {
    /**
     * 删除有序链表中重复的元素-I
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public static ListNode deleteDuplicates(ListNode head) {
        // 如果链表为空或者只有一个结点,不会有重复的元素,返回原链表
        if (head == null || head.next == null) {
            return head;
        }

        // pre记录上一个未重复的结点
        // next为从第二个节点开始判断是否有重复元素
        ListNode pre = head, next = head.next;
        // 遍历链表
        while (next != null) {
            // 如果当前结点的值和pre的值相同,则要删掉当前结点,修改pre的next指针即可
            if (pre.val == next.val) {
                pre.next = next.next;
            } else {
                // 如果当前结点未重复,则更新pre
                pre = next;
            }
            next = next.next;
        }
        return head;
    }

    public static void main(String[] args) {
        ListNode head = ListNode.testCase6();
        System.out.println("原链表为");
        ListNode.print(head);

        System.out.println("删除有序链表中重复的元素后的链表为");
        ListNode.print(deleteDuplicates(head));
    }
}
$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
Believe in the power of persistence!

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!