算法系列——Remove Duplicates from Sorted List II

来源:互联网 发布:恺英网络造假 编辑:程序博客网 时间:2024/06/01 10:01

题目描述

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

解题思路

引入虚拟头结点来辅助,跳过值重复的结点。

程序实现

public class Solution {    public ListNode deleteDuplicates(ListNode head) {        if(head==null||head.next==null)            return head;        ListNode dummyHead=new ListNode(-1);        ListNode p=dummyHead;        p.next=head;        ListNode cur=head;        while(cur!=null){            //跳过重复元素            while(cur.next!=null&&cur.next.val==cur.val)                cur=cur.next;            if(p.next==cur)                p=p.next;            else                p.next=cur.next;            cur=cur.next;        }        return dummyHead.next;    }}
阅读全文
0 0
原创粉丝点击