113.Remove Duplicates from Sorted List II-删除排序链表中的重复数字 II(中等题)

来源:互联网 发布:三角刮刀淘宝 编辑:程序博客网 时间:2024/06/09 18:13

删除排序链表中的重复数字 II

  1. 题目

    给定一个排序链表,删除所有重复的元素只留下原链表中没有重复的元素。

  2. 样例

    给出 1->2->3->3->4->4->5->null,返回 1->2->5->null
    给出 1->1->1->2->3->null,返回 2->3->null

  3. 题解

对链表进行遍历,相邻节点不同就跳过,相同则继续遍历直至结束或找到不同节点,再进行删除操作。

/** * Definition for ListNode * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    /**     * @param ListNode head is the head of the linked list     * @return: ListNode head of the linked list     */    public static ListNode deleteDuplicates(ListNode head) {        ListNode result = new ListNode(1);        result.next = head;        ListNode pre = result;        while (head != null && head.next != null)        {            if (head.val != head.next.val)            {                pre = head;                head = head.next;                continue;            }            while (head.next != null && head.val == head.next.val)            {                head = head.next;            }            pre.next = head.next;            head = pre.next;        }        return result.next;    }}

Last Update 2016.10.9

0 0
原创粉丝点击