LeetCode 83. Remove Duplicates from Sorted List

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjxxyz123/article/details/79981103

问题描述

  • Given a sorted linked list, delete all duplicates such that each element appear only once.
    For example,
    Given 1->1->2, return 1->2.
    Given 1->1->2->3->3, return 1->2->3.
  • 地址

问题分析

  • 只保留重复中的第一个即可

代码实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode preNode = head;
        ListNode curNode = null;
        while (preNode != null) {
            curNode = preNode.next;
            while (curNode != null && curNode.val == preNode.val){
                curNode = curNode.next;
            }
            preNode.next = curNode;
            preNode = curNode;
        }
        return head;
    }
}
阅读更多

没有更多推荐了,返回首页