【数据结构】算法 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;
    }
}
上一篇:Spring Boot从入门到精通(八)日志管理实现和配置信息分析


下一篇:如果其他值重复,如何更新MySQL表中的值?