原创

[百战LeetCode][18.删除有序链表中重复元素-II]


==========================努力奋斗财源广进==========================

一、算法题目

给出一个升序排序的链表,删除链表中的所有重复出现的元素,只保留原链表中只出现一次的元素。

二、题解

1、我的题解

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode deleteDuplicates (ListNode head) {
        // write code here
        if(head == null) return head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode cur = dummy;
        while(cur.next != null && cur.next.next != null){
            if(cur.next.val == cur.next.next.val){
                int tem = cur.next.val;
                while(cur.next != null && cur.next.val == tem){
                    cur.next = cur.next.next;
                }
            }else{
                cur = cur.next;
            }
        }
        return dummy.next;
    }
}

2、优秀题解

//待定

三、解法心得

只是使用了一个指针,但是新增了一个头节点起了很大的作用。在if条件里面新建临时变量保存当前重复的值,如果重复就覆盖前一个节点。直到出现新值

四、自我监督

评论区记录复习记录

算法刷题
  • 作者:北斗七点半联系作者
  • 发表时间:2022-07-16 20:14
  • 版权声明:禁止转载
  • 非公众号转发
  • 评论