LeetCode 之 删除链表重复的元素(简单 链表)

问题描述

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

输入: 1->1->2
输出: 1->2

示例 2:

输入: 1->1->2->3->3
输出: 1->2->3

简单的一批,直接代码

默认节点类

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
 public ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode pre = head;
        ListNode next = head.next;

        while (next.next != null) {
            if (next.val == pre.val) {
                next = next.next;
                pre.next = next;
            }else {
                pre = next;
                next = next.next;
            }
        }
        if (next.val == pre.val){
            pre.next = null;
        }
        return  head;
    }

下边是大神写的

public ListNode deleteDuplicates(ListNode head) {
    ListNode current = head;
    while (current != null && current.next != null) {
        if (current.next.val == current.val) {
            current.next = current.next.next;
        } else {
            current = current.next;
        }
    }
    return head;
}

猜你喜欢

转载自blog.csdn.net/qq_27817327/article/details/83410588