1. 程式人生 > >LeetCode 83 —— 刪除排序連結串列中的重複元素

LeetCode 83 —— 刪除排序連結串列中的重複元素

1. 題目

2. 解答

從前向後遍歷連結串列,如果下一個結點的值和當前結點的值相同,則刪除下一個結點,否則繼續向後遍歷。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        
        if (head == NULL || head->next == NULL) return head;
        
        ListNode *temp = head;
            
        while (temp && temp->next)
        {
            if (temp->val == temp->next->val)
            {
                temp->next = temp->next->next;
            }
            else
            {
                temp = temp->next;
            }
        }
        
        return head;
    }
};

獲取更多精彩,請關注「seniusen」!