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

Example

Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: head node
     */
    ListNode *deleteDuplicates(ListNode *head) {
        // write your code here
    if (head == NULL) {
        return NULL;
    }
    ListNode* cur = head;
    ListNode* next;
    while (cur != NULL && cur->next != NULL) {
        if (cur->val == cur->next->val) {
            next = cur->next->next;
            cur->next = next;
        } else {
            cur = cur->next;
        }
    }
    return head;
    }
};

results matching ""

    No results matching ""