美文网首页
83. Remove Duplicates from Sorte

83. Remove Duplicates from Sorte

作者: evil_ice | 来源:发表于2016-12-27 20:27 被阅读4次

题目83. 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.

public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        
        int preNum = head.val;
        ListNode node = head.next;
        ListNode tail = head;
        while(node != null){
            if(node.val != preNum){
                tail.next = node;
                tail = tail.next;
            }
            preNum = node.val;
            node = node.next;
        }
        tail.next = null;
        return head;
    }
}

相关文章

网友评论

      本文标题:83. Remove Duplicates from Sorte

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