链表-删除排序链表中的重复元素-简单

描述
给定一个排序链表,删除所有重复的元素每个元素只留下一个。
您在真实的面试中是否遇到过这个题?  是
样例
给出 1->1->2->null,返回 1->2->null

给出 1->1->2->3->3->null,返回 1->2->3->null

题目链接

程序


**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param head: head is the head of the linked list
     * @return: head of linked list
     */
    ListNode * deleteDuplicates(ListNode * head) {
        // write your code here
        if(head == NULL || head->next == NULL)
            return head;
        ListNode *pre = NULL, *cur = head;
        while(cur != NULL){
            if(pre != NULL && pre->val == cur->val){
                pre->next = cur->next;
                cur = pre->next;
            }
            else{
                pre = cur;
                cur = pre->next;
            }
        }
        return head;
    }
};


猜你喜欢

转载自blog.csdn.net/qq_18124075/article/details/80966273
今日推荐