Fork me on GitHub

【数据结构】算法 Remove Duplicates from Sorted List删除排序链表中的重复元素

Remove Duplicates from Sorted List删除排序链表中的重复元素

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次

输入: 1->1->2
输出: 1->2
输入: 1->1->2->3->3
输出: 1->2->3
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if (head==null){
            return null;
        }
        ListNode p = head;
        while(p.next!=null){
            if (p.val == p.next.val){
                p.next = p.next.next;
            }
            else{
                p = p.next;
            }
        }
        return head;
    }
}
posted @ 2021-03-16 09:56  WilliamCui  阅读(67)  评论(0编辑  收藏  举报