zoukankan      html  css  js  c++  java
  • [LeetCode] 83. Remove Duplicates from Sorted List ☆(从有序链表中删除重复项)

    描述

    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;
        }
    }

    相似问题:删除链表中的重复节点 (难一点)

  • 相关阅读:
    测试打印功能
    绘图
    图片验证码
    图片防盗
    图片水印
    surface 译
    ViewManager 译
    WindowId 译
    Display
    LayoutParams
  • 原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/10777216.html
Copyright © 2011-2022 走看看