[leetcode] 【链表】83. Remove Duplicates from Sorted List

来源:互联网 发布:聚游网络散人 编辑:程序博客网 时间:2024/06/08 04:47

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.


题意

一个排好序的链表,把 里面的重复元素删除掉。

题解

两个指针指向前一个和后一个元素,相同则删除掉后一个,否则继续遍历。

/** * 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) return head;        for(ListNode *prev=head,*cur=head->next;cur;cur=cur->next)        {            if(prev->val==cur->val)            {                prev->next=cur->next;                delete cur;            }            else prev=cur;        }        return head;    }};


0 0
原创粉丝点击