美文网首页
Remove Duplicates from Sorted Li

Remove Duplicates from Sorted Li

作者: 小明今晚加班 | 来源:发表于2019-02-25 20:27 被阅读0次

题目描述
Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

分析:给定一个有序链表,去除重复元素,并返回一个新链表。

我的Code如下:

/**
 * 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){
            return head;
        }
        ListNode pre = head;
        ListNode cur = head.next;
        while(cur != null){
            if(pre.val == cur.val){
                pre.next = cur.next;
            }else{
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }
}

相关文章

网友评论

      本文标题:Remove Duplicates from Sorted Li

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