首页 > 编程语言 > 详细

[LeetCode] 83. Remove Duplicates from Sorted List ☆(从有序数组中删除重复项)

时间:2019-04-27 00:07:42      阅读:151      评论:0      收藏:0      [点我收藏+]

描述

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2
Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

有序链表去重。

 

解析

移除给定有序链表的重复项,那么我们可以遍历这个链表,每个结点和其后面的结点比较,如果结点值相同了,我们只要将前面结点的next指针跳过紧挨着的相同值的结点,指向后面一个结点。这样遍历下来,所有重复的结点都会被跳过,留下的链表就是没有重复项的了。

 

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    //me
    public ListNode deleteDuplicates(ListNode head) {
        if (null == head) {
            return head;
        }
        ListNode cur = head;
        ListNode next = cur.next;
        while (cur != null && next != null) {
            while (next != null && cur.val == next.val) {
                cur.next = next.next;
                next = next.next;
            }
            cur = cur.next;
        }
        return head;
    }
}

 

[LeetCode] 83. Remove Duplicates from Sorted List ☆(从有序数组中删除重复项)

原文:https://www.cnblogs.com/fanguangdexiaoyuer/p/10777216.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!