美文网首页
LeetCode每日一题:remove duplicates f

LeetCode每日一题:remove duplicates f

作者: yoshino | 来源:发表于2017-05-18 09:13 被阅读5次

问题描述

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

问题分析

删除链表中的重复节点,链表中很常见的操作,Java不需要考虑释放结点,而C++必须删除无用节点

代码实现

public ListNode deleteDuplicates(ListNode head) {
        if (head == null) return null;
        ListNode curNode = head;
        while (curNode != null) {
            while (curNode.next != null && curNode.val == curNode.next.val) {
                curNode.next = curNode.next.next;
            }
            curNode = curNode.next;
        }
        return head;
    }

相关文章

网友评论

      本文标题:LeetCode每日一题:remove duplicates f

      本文链接:https://www.haomeiwen.com/subject/jgajxxtx.html