83Remove Duplicates from Sorted List

来源:互联网 发布:淘宝卖家中心没有了 编辑:程序博客网 时间:2024/04/29 09:55

题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list/

题目:

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.

解题思路:
这道题很简单,不做过多累述。
需要注意的是,每次更新 p 指针后都应该判断其是否已为空。为空直接跳出循环

代码实现:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode deleteDuplicates(ListNode head) {        if(head == null)            return head;        ListNode p = head;        while(p.next != null) {            while(p.next != null && p.next.val == p.val)                p.next = p.next.next;            if(p.next != null)                p = p.next;        }        return head;    }}
164 / 164 test cases passed.Status: AcceptedRuntime: 1 ms
0 0
原创粉丝点击