Leet Code OJ 83. Remove Duplicates from Sorted List [Difficulty: Easy]

Posted Lnho

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leet Code OJ 83. Remove Duplicates from Sorted List [Difficulty: Easy]相关的知识,希望对你有一定的参考价值。

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

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

翻译:
给定一个排序号的链表,删除所有的重复元素,保证每个元素只出现一次。

分析:
在当前节点删除下一节点,会比较容易操作,只需要修改next指针。

代码:

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

        }
        return head;
    }
}

以上是关于Leet Code OJ 83. Remove Duplicates from Sorted List [Difficulty: Easy]的主要内容,如果未能解决你的问题,请参考以下文章

Leet Code OJ 26. Remove Duplicates from Sorted Array [Difficulty: Easy]

Leet Code OJ 203. Remove Linked List Elements [Difficulty: Easy]

Leet Code OJ 1. Two Sum [Difficulty: Easy]

Leet Code OJ 223. Rectangle Area [Difficulty: Easy]

Leet Code OJ 338. Counting Bits [Difficulty: Easy]

Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]