[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

移除有序链表中的重复项,返回新链表。定义1个指针指向链表的第一个元素,然后第一个元素和第二个元素比较,如果重复,则删掉第二个元素,如果不重复,指针指向第二个元素。

Java:

/**
 * 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 || head.next == null) return head;
        ListNode c = head;
        while (c.next != null) {
            if (c.val == c.next.val) {
                c.next = c.next.next;
            } else {
                c = c.next;
            }
        }
        return head;
    }
}  

Python:

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur = head
        while cur:
            runner = cur.next
            while runner and runner.val == cur.val:
                runner = runner.next
            cur.next = runner
            cur = runner
        return head

    def deleteDuplicates2(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head: return head
        if head.next:
            if head.val == head.next.val:
                head = self.deleteDuplicates(head.next)
            else:
                head.next = self.deleteDuplicates(head.next)
        return head 

Python: wo

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return None
        
        dummy = ListNode(0)
        dummy.next = head

        while head and head.next:            
            if head.val == head.next.val:
                head.next = head.next.next
            else:             
                head = head.next   
            
        return dummy.next   

C++:

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        if (!head || !head->next) return head;
        
        ListNode *start = head;
        while (start && start->next) {
            if (start->val == start->next->val) {
                ListNode *tmp = start->next;
                start->next = start->next->next;
                delete tmp;
            } else start = start->next;
        }
        return head;
    }
};

  

类似题目:

[LeetCode] 82. Remove Duplicates from Sorted List II 移除有序链表中的重复项 II

[LeetCode] 19. Remove Nth Node From End of List 移除链表倒数第N个节点

[LeetCode] 203. Remove Linked List Elements 移除链表元素

 

All LeetCode Questions List 题目汇总

posted @ 2018-03-14 05:52  轻风舞动  阅读(301)  评论(0编辑  收藏  举报